How do I add a newline to a TextView in Android?

2019-01-04 09:15发布

When I define a TextView in xml, how do I add a new line to it? \n seems not to work.

<TextView
   android:id="@+id/txtTitlevalue"
   android:text="Line1: \n-Line2\n-Line3"
   android:layout_width="54dip"
   android:layout_height="fill_parent"
   android:textSize="11px" />

26条回答
虎瘦雄心在
2楼-- · 2019-01-04 09:34

for the new line in TextView just add \n in middle of your text it works..

查看更多
淡お忘
3楼-- · 2019-01-04 09:37

You need to put \n in the file string.xml

<string name="strtextparkcar">press Park my Car to store location \n</string>
查看更多
姐就是有狂的资本
4楼-- · 2019-01-04 09:37

If the TextView is in any Layout (LinearLayout for example), try to change the orientation attribute to vertical as android:orientation="vertical" for the layout or change the TextView attribute android:singleLine="true" to create a new line after it.

查看更多
劫难
5楼-- · 2019-01-04 09:38

I think this has something to do with your HTM.fromHtml(subTitle) call: a "\n" doesn't mean bupkis to HTML. Try <br/> instead of "\n".

查看更多
Luminary・发光体
6楼-- · 2019-01-04 09:38

Tried all the above, did some research of my own resulting in the following solution for rendering line feed escape chars:

string = string.replace("\\\n", System.getProperty("line.separator"));
  1. Using the replace method you need to filter escaped linefeeds (e.g. '\\\n')

  2. Only then each instance of line feed '\n' escape chars gets rendered into the actual linefeed

For this example I used a Google Apps Scripting noSQL database (ScriptDb) with JSON formated data.

Cheers :D

查看更多
乱世女痞
7楼-- · 2019-01-04 09:39

This works fine. Check it for your app.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 1\nText 2\nText 3"/>
查看更多
登录 后发表回答