Darth Coder
Darth Coder

Reputation: 1798

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

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?

Upvotes: 5

Views: 3442

Answers (4)

amin vojoodi
amin vojoodi

Reputation: 1

this worked for me : android:includeFontPadding="false"

Upvotes: 0

Emmanuel
Emmanuel

Reputation: 13233

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.

Upvotes: 7

Hirak Chhatbar
Hirak Chhatbar

Reputation: 3181

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.

Upvotes: 1

N Sharma
N Sharma

Reputation: 34507

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" />

Upvotes: 3

Related Questions