有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我无法在listview中居中显示文本

我有以下xml:

<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:ads="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:orientation="vertical"
    tools:context=".AllJokes" 
    安卓:background="@drawable/background">

    <ListView
              安卓:id="@+id/allJokesList"
              安卓:layout_width="fill_parent"
              安卓:layout_height="0dp"
              安卓:layout_weight="1"
              安卓:gravity="center">
    </ListView>


              <com.google.安卓.gms.ads.AdView 安卓:id="@+id/adView"

                    安卓:layout_width="fill_parent"
                    安卓:layout_height="wrap_content"
                    安卓:gravity="center_vertical"
                    ads:adUnitId="ca-app-pub-code/code"
                    ads:adSize="BANNER"
                />

</LinearLayout>

正如您所看到的,我试图使用安卓:gravity="center_vertical"listView的文本居中,但没有成功。我也试着通过:安卓:gravity="center"来完成它,但它总是被搁置

同样在java代码中,我通过以下方式为listView设置白色背景:

listView.setBackgroundColor(Color.WHITE);

是不是把事情搞砸了

为什么会这样

我知道我错过了一些非常小和基本的东西,但作为一个初学者,我无法发现它

编辑:

以下是我用于将项目添加到列表视图的代码:

adapter = new ArrayAdapter<String>(this, 安卓.R.layout.simple_list_item_1, new ArrayList<String>());
        adapter.clear();
        adapter.addAll(globals.getMyStringArray());

        listView = (ListView) findViewById(R.id.allJokesList);
        listView.setAdapter(adapter);
        listView.setBackgroundColor(Color.WHITE);

其中globals.getMyStringArray()已填充值


共 (1) 个答案

  1. # 1 楼答案

    用这个。我复制了同样的安卓系统。R.布局。简单的列表项目布局,但改变了安卓:gravity=“center”

    R.布局。自定义\u简单\u列表\u项目

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
    

    更改代码

     adapter = new ArrayAdapter<String>(this, R.layout.custom_simple_list_item, new ArrayList<String>());