Center text objects in a ListView

How can I horizontally align the elements of ListView text in my Layout ?
Honestly, at least an hour before I asked 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> 
+4
source share
3 answers

You need to create your own layout for your list 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, you have to do it

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

I could not center the elements in the ListView if LisView itself was defined using android: layout_width = "wrap_content" This does not, because this parameter should only affect the position of the ListView, and not its elements.

In any case, changing the width of the list in match_parent allows you to center the elements with their gravity attributes (layout_).

+3
source

In the TextView layout for your custom ListView XML file, use android:gravity="center" . It will do it.

-4
source

Source: https://habr.com/ru/post/1343700/


All Articles