Wednesday, May 30, 2012

How do I center text horizontally and vertical in a TextView in Android?


How do I center the text horizontally and vertically in a TextView in android, so that it appears exactly in the middle of the screen?



Source: Tips4all

7 comments:

  1. I'm assuming you're using XML layout.

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_vertical|center_horizontal"
    android:text="@string/**yourtextstring**"
    />

    ReplyDelete
  2. android:gravity="center"


    will do the trick

    ReplyDelete
  3. You can also set it up dynamically using:

    textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

    ReplyDelete
  4. android:layout_centerInParent="true"


    This works when used with a RelativeLayout where the layout's height & width are set to wrap_content.

    ReplyDelete
  5. If you are using TableLayout make sure to set the gravity of the TableRows to center, too.
    Otherwise it will not work.
    At least it didn't work with me until i set the gravity of the TableRow to center.

    For Example like this:

    <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center">
    <TextView android:text="@string/chf" android:id="@+id/tv_chf" android:layout_weight="2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center"></TextView>
    </TableRow>

    ReplyDelete
  6. You can set textview in horizontaly and vartically using below method.
    add one layout set the layout gravity horizontal and vertical and add the textview in that layout so you have textview in center horizontal and vartical

    ReplyDelete
  7. android:layout_centerhorizontal="true"


    and

    android:layout_centervertical="true"

    ReplyDelete