It sounds like you want to place your items within a parent with layout_width="wrap_content"
and center the whole parent.
Something like this, perhaps?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView android:text="Content above..."
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<TextView android:text="One"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:text="Two"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:text="Three"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView android:text="Content below..."
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Remember the difference between gravity
and layout_gravity
. The gravity
attribute refers to the view's content. layout_gravity
(and all other attributes prefixed with layout_
) refers to the view's layout within its parent.
Edit: If you're looking to format ListView items similarly, try something like this as your list item layout with the ListView itself using layout_width="fill_parent"
and layout_height="fill_parent"
:
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:weightSum="2"
android:gravity="center">
<TextView android:id="@+id/text"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Change the content of the TextView with id text
in each list item in the usual way. The minHeight
setting pulled from the current theme will make sure it stays a good size for touch.
The uniform centering in this case is handled by a combination of the weightSum
and gravity
on the LinearLayout and the layout_weight
on the TextView. The TextView's weight divided by its parent's weightSum will determine the percentage of horizontal space the LinearLayout will give it. In the example above it will get 1/2 the available horizontal space, but centered.
Since ListView never knows the content of list items that are not currently onscreen there is no way to have it measure the text of every item in your adapter to center the content perfectly. You will have to approximate it using a list item layout like the example above.