2

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.

double-beep
  • 5,031
  • 17
  • 33
  • 41
HannahMitt
  • 1,010
  • 11
  • 14
  • Having a similar problem. I'm guessing that `gravity` doesn't work in conjunction with `layout_weight`. What was your solution? – SMBiggs Sep 08 '17 at 03:20

3 Answers3

1

What you are looking for is textAlignment in your case:

android:textAlignment="center"
geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
igarciad
  • 36
  • 3
0

try with center_vertical and center_horizontal in the textview attribute

android:gravity="center_vertical|center_horizontal"
Nambi
  • 11,944
  • 3
  • 37
  • 49
  • Based on this: http://developer.android.com/reference/android/view/Gravity.html#CENTER center_vertical|center_horizontal should be identical to center – HannahMitt Mar 08 '14 at 16:02
  • @HannahMitt Did you tried with center_vertical and center_horizontal – Nambi Mar 08 '14 at 16:04
0

I suspect you mean layout_gravity, not gravity

See: Gravity and layout_gravity on Android

Community
  • 1
  • 1
G. Blake Meike
  • 6,615
  • 3
  • 24
  • 40
  • I don't, I wanted the internal gravity of the TextView to be center to center the text inside it. – HannahMitt Mar 08 '14 at 17:09
  • Got it. I cannot reproduce this problem with the code you show here. is there 1) any layout in the style; 2) another container, holding the LinearLayout? – G. Blake Meike Mar 08 '14 at 17:36