Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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?
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.
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
I'm assuming you're using XML layout.
ReplyDelete<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:text="@string/**yourtextstring**"
/>
android:gravity="center"
ReplyDeletewill do the trick
You can also set it up dynamically using:
ReplyDeletetextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
android:layout_centerInParent="true"
ReplyDeleteThis works when used with a RelativeLayout where the layout's height & width are set to wrap_content.
If you are using TableLayout make sure to set the gravity of the TableRows to center, too.
ReplyDeleteOtherwise 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>
You can set textview in horizontaly and vartically using below method.
ReplyDeleteadd 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
android:layout_centerhorizontal="true"
ReplyDeleteand
android:layout_centervertical="true"