Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to center text horizontally and vertically in a TextView?

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?
by

2 Answers

RoliMishra
Apply gravity:

TextView txtView = (TextView) findViewById(R.id.txtView);
txtView.setGravity(Gravity.CENTER_HORIZONTAL);

For vertical:

txtView.setGravity(Gravity.CENTER_VERTICAL);

In XML:

<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="@string/Hello_World"
/>
Sonali7
The following code can be implemented to center text horizontally and vertically in a TextView:

<TextView  
android:id="@+id/textView"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text="@strings/text"
/>

Login / Signup to Answer the Question.