HannahMitt
HannahMitt

Reputation: 1020

TextView with weight is failing to center text horizontally

I have a view with 2 TextViews in a horizontal LinearLayout, each with a weight of 1.

The second TextView was like this:

<TextView
                android:id="@+id/info_button"
                style="@style/TextBlue"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:background="@drawable/bg_ten_percent_black_selector"
                android:layout_height="@dimen/card_button_height"
                android:text="@string/shop_info"
                android:gravity="center"
                />

For some reason, the text would not center horizontally when rendered. However, if I performed a touch on it, it would center then.

I have a fix where I wrap it in an extra LinearLayout which is given the weight, and center the TextView within that, but I was wondering why that workaround is effective when this isn't.

Also, what extra information might be needed here, since this method of centered text usually works. The views are inflated and added as ListView header.

Upvotes: 2

Views: 1064

Answers (3)

igarciad
igarciad

Reputation: 36

What you are looking for is textAlignment in your case:

android:textAlignment="center"

Upvotes: 1

G. Blake Meike
G. Blake Meike

Reputation: 6715

I suspect you mean layout_gravity, not gravity

See: Gravity and layout_gravity on Android

Upvotes: 0

Nambi
Nambi

Reputation: 12042

try with center_vertical and center_horizontal in the textview attribute

android:gravity="center_vertical|center_horizontal"

Upvotes: 0

Related Questions