Center text items in ListView

柔情痞子 提交于 2019-12-10 05:31:32

问题


How can I horizontally center-align text items of the ListView in my Layout?
Honestly, I googled for at least an hour before asking such a basic question.

Thanks.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="Remind..." />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:baselineAligned="false"
        android:orientation="horizontal" >

        <ListView
            android:id="@+id/listviewTimeInterval"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:scrollbars="none" />

         <-- . . . --/>
         <-- more lists of the same kind--/>
         <-- . . .--/>

    </LinearLayout>

</LinearLayout>

回答1:


You need to create your own layout for your listview item, something like this

Example:

textcenter.xml:

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center" >
    <TextView
        android:id="@id/textItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Then, in your code, your have to do this

ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.textcenter, R.id.textItem, functions);
listView.setAdapter(ad);



回答2:


I found it impossible to center the items in a ListView if the LisView itself is defined with android:layout_width="wrap_content" This does not make sence, because this parameter should only affect the position of the ListView and not its elements.

Anyway, changing the width of the list to match_parent allows to center the items with their (layout_)gravity attributes.




回答3:


In the layout of the TextView for your customized ListView xml file use android:gravity="center" . That'll do it.



来源:https://stackoverflow.com/questions/16168424/center-text-items-in-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!