How to center two-line text in a TextView on Android?

I want it to look like this:

| two | | lines | 

Here is the current layout not working at all.

 <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="two\nlines" android:layout_gravity="center_vertical" android:layout_centerInParent="true"/> </RelativeLayout> 

Any idea? Thank!

+60
android text multiline textview text-alignment
Jan 25 2018-11-11T00:
source share
6 answers

If you just want to center it (I assume that \n works to split the lines), just add android:gravity="center_horizontal" , not layout_gravity .
Using a gravity layout moves the actual TextView, using gravity affects the content of the TextView.

+181
Jan 25
source share

I had to add both gravity and layout_gravity to align the TextView and its contents

 android:gravity="center_horizontal" android:layout_gravity="center_horizontal" 
+8
Jan 16 '17 at 2:56 on
source share

You can use:

 TextView tv = (TextView) findViewById(R.id.the_text_view); tv.setText(Html.fromHtml("two"+"\n"+"lines")); 
+2
May 9 '12 at 2:08 pm
source share

I think you should do it with Java:

 <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical"> <TextView android:id="@+id/the_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_centerInParent="true"/> </RelativeLayout> 

Then:

 TextView tv = (TextView) findViewById(R.id.the_text_view); tv.setText(Html.fromHtml("two<br/>lines")); 
+1
Jan 25 2018-11-11T00:
source share

if your width is wrap_content, you should set gravity and layout_gravity as "center_horizontal"

 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="two\nlines" android:layout_gravity="center_horizontal" android:gravity="center_horizontal"/> 

However, if your width is match_parent, you will need to set gravity to center_horizontal

 <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="two\nlines" android:gravity="center_horizontal"/> 

Hope this helps!

0
Oct 02 '17 at 7:50
source share

Add Property

 android:lines="2" 

where 2 there are no lines, you can set this as your requirement

-2
Dec 11 '14 at 7:09
source share



All Articles