20
<TextView
        android:layout_height="30dp"
        android:text="@string/list_title"
        android:layout_gravity="center"
        android:layout_width="fill_parent"
        android:textSize="@dimen/title_size"
        android:textAlignment="center"
        android:layout_alignParentTop="true"
        android:background="@color/white"
        android:id="@+id/list_title"
        />

Is the first element in a RelativeLayout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">

But the text in the TextView will not center. I cannot understand why as all gravities and the textAlignment property are set to "center".

What am I doing wrong?

Tom Macdonald
  • 6,433
  • 7
  • 39
  • 59

3 Answers3

62

Add android:gravity="center" to your textView

Manishika
  • 5,478
  • 2
  • 22
  • 28
  • 2
    Ah, thanks, I was using android:layout_gravity I see now. What's the difference? – Tom Macdonald Nov 26 '13 at 10:56
  • 5
    android:gravity applies graivity to the content of the view, while android:layout_gravity applies gravity to the view itself inside its parent. – Jigar Pandya Nov 26 '13 at 10:56
  • 1
    I see, so android:gravity on the parent is equivalent to android:layout_gravity on the child then, in terms of the effect it has on the child? – Tom Macdonald Nov 26 '13 at 11:00
  • 1
    Details on the difference between `android:textAlignment` and `android:gravity`: https://stackoverflow.com/a/16197308/2848676 – Michael Osofsky Sep 03 '19 at 19:05
3

Try this:

<TextView
        android:layout_height="30dp"
        android:text="@string/list_title"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:textSize="@dimen/title_size"
        android:textAlignment="center"
        android:layout_alignParentTop="true"
        android:background="@color/white"
        android:id="@+id/list_title"
        />
Damien R.
  • 3,383
  • 1
  • 21
  • 32
  • 4
    Here we care about answers with good explanations, not just code. Only post an answer if it really solves the question and you can explain how. To improve your future answers, take a look the the guide [how do I write a good answer](https://stackoverflow.com/help/how-to-answer). – Erick Petrucelli Dec 14 '18 at 13:24
0

if your textview is inside a constraintLayout then set its width to 0dp and then apply these constraints

app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:textAlignment="center"