I am relatively new to the Android SDK and am working with a TextView amongst other components on my activity UI. When I set the width to wrap_content
and use layout_gravity
, I am able to center the TextView in my parent container.
However, I now need to give the TextView a background that stretches fully along the width of the parent and so I set the width to match_parent
. Once I do this, neither layout_gravity
nor textAlignment="center"
are able to center the text within the view. This is the code I am using:
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="@string/trackName"
android:textColor="#ffffff"
android:layout_gravity="center"
android:textSize="28sp"
android:paddingTop="7dp"
android:paddingLeft="20dp"
android:background="#99000000" />
This is what the activity UI looks like right now:
How can I fix this and align my text to the center of the TextView control?
You should use android:gravity
. As the docs say:
gravity Specifies how an object should position its content, on both the X and Y axes, within its own bounds.
layout_gravity Standard gravity constant that a child supplies to its parent. Defines how the child view should be positioned, on both the X and Y axes, within its enclosing layout.