Alex Rivera | Logout

How do I center text horizontally and vertically in a TextView?

Asked 2009-01-11T00:27:55.617
2341

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

Edit
Report

2 Answers

41

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>
answered 2011-05-13T11:57:15.410
39

You need to set TextView Gravity (Center Horizontal & Center Vertical) like this:

android:layout_centerHorizontal="true"   

and

android:layout_centerVertical="true"

And dynamically using:

textview.setGravity(Gravity.CENTER);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
answered 2012-05-15T05:03:02.320

Your Answer