How to center a Textview?

Asked

Viewed 3,630 times

4

How to center horizontal text on TextView that is to center on 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"/>

2 answers

6


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

This way, it will center 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 you can see here on android documentation.

  • Valeu worked out well

  • @Rodolfo good that solved. Remember to mark as accepted, to serve as reference for other people with similar doubt. D

  • and if I want to center with center and then and also leave it on the right side? ie centered and right

1

To set in time to popular the field: campo.setGravity(Gravity.CENTER_HORIZONTAL);

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

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

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

  • But there is no way to do this directly in XML!? So it would start as it wants to!

  • Yes, it can be done in XML as Articuno responded earlier. inside the Textview tag add android:Gravity="center_horizontal" or other position you need

  • Oops. His answer appeared in the review, so we could not see the response of Articuno. Quiet companion! ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.