How to center a TextView?

4

How to center the horizontal text in TextView , ie center in the top and bottom line.

        <TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="right"
        android:text="Texto"/>
    
asked by anonymous 31.01.2016 / 12:57

2 answers

6
    <TextView
    android:id="@+id/txt"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="Texto"/>

In this way, you will center both horizontally and vertically. If you need only horizontally:

    <TextView
    android:id="@+id/txt"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:text="Texto"/>

Or programmatically:

seuTexview.setGravity(Gravity.CENTER);

More details can be found here at documentation android .

    
31.01.2016 / 13:03
1

To be at the time of popular the field: campo.setGravity(Gravity.CENTER_HORIZONTAL);

To return to the initial state campo.setGravity(Gravity.NO_GRAVITY);

To set the left: campo.setGravity(Gravity.LEFT);

To set the right: campo.setGravity(Gravity.RIGHT);

    
19.07.2018 / 20:29