Reputation: 3525
I have a LinearLayout with three TextViews foo, bar and baz. foo should be on the left, bar centered and baz on the right. This is what I got so far:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="foo" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bar" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="baz" />
</LinearLayout>
The problem I have is that bar is only centered, when foo and baz have the same size. Furthermore, the text of baz may change during program execution, making bar jump around to maintain equal distance to foo and baz.
I would like bar to always be centered within the LinearLayout, no matter the (possibly changing) size of foo and baz. How can I archive this?
Upvotes: 1
Views: 41
Reputation: 1564
This should be what you're looking for. It will keep the middle TextView
in the middle of the layout regardless of what the values of the left and right TextView
s are (notice I've changed the text lengths from your foo and baz values).
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="asdfasdfasdf" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bar" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:text="dfdfdf" />
</LinearLayout>
Upvotes: 1