Advertisement
Advertisement


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


Question

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?

2018/04/06
1
2069
4/6/2018 2:40:14 PM

Accepted Answer

I'm assuming you're using XML layout.

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center"
    android:text="@string/**yourtextstring**"
/>

You can also use gravity center_vertical or center_horizontal according to your need.

and as @stealthcopter commented in java: .setGravity(Gravity.CENTER);

2018/07/10
3132
7/10/2018 4:11:32 PM

android:gravity="center" 

This will do the trick

2015/03/22

You can also set it up dynamically using:

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
2009/11/21

android:layout_centerInParent="true"

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

2011/11/11

You can also use the combination:

android:gravity="left|center"

Then, if textview width is more than "fill_parent" the text will still be aligned to left (not centered as with gravity set only to "center").

2013/07/26

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"        
/>
2015/02/17

Source: https://stackoverflow.com/questions/432037
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]