Unable to center the text in TextView when width is set to 'match_parent'

3.3k views Asked by At

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:

enter image description here

How can I fix this and align my text to the center of the TextView control? Please help!

3

There are 3 answers

0
Emmanuel On BEST ANSWER

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.

0
N Sharma On

Use gravity instead of layout_gravity

Difference between them

android:gravity sets the gravity of the content of the View its used on and android:layout_gravity sets the gravity of the View or Layout in its parent.

Try this that should solve your problem.

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="@string/trackName"
    android:textColor="#ffffff"
    android:gravity="center"
    android:textSize="28sp"
    android:paddingTop="7dp"
    android:paddingLeft="20dp"
    android:background="#99000000" />
0
Hirak Chhatbar On
android:gravity="center_horizontal"

Difference between gravity and layout_gravity :

layout_gravity means the gravity of the widet in its layout. you have used width as match_parent. So your textview is already occupying all the space.

gravity means the gravity of the content of that view. i.e. gravity of the text in your textview. u have to place that text in the center, not the textview.