3

Android 换行符(\n) 在TextView中显示不正常的问题

 3 years ago
source link: http://www.androidchina.net/3501.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Android 换行符(\n) 在TextView中显示不正常的问题 – Android开发中文站
你的位置:Android开发中文站 > Android开发 > 新手入门 > Android 换行符(\n) 在TextView中显示不正常的问题

问题描述

在Android开发,使用TextView设置换行的时候,会有这种情况:

1、如果直接在XML文件中写入”aaaaa\nbbbb”可以换行,显示为:

   aaaaa
   bbbbb

2、在Java文件中用textViewObj.setText(“aaaa\nbbbb”)也可以换行,显示为:

   aaaaa
   bbbbb

3、将“aaaaa\nbbbb”封装到一个类People里面的Description字段后,
  在Java代码中使用textView.setText(people.getDescription())。显示为:

  aaaaa\nbbbb

上面第3点就是问题所在,不能正常换行。

问题分析:

很简单,在程序运行的时候显示为“aaaa\nbbbb”,那么必须对TextView设置了“aaaa\\nbbbb”,
这里多了一个“\”, 对象所携带的字符串的转义已经被消除了,

至于为什么会被消除, 去问Google的CEO去吧.

通过以下的方法传递一个对象之后, 如果这个对象包含了字符串成员变量, 那么, 这个字符串所包含的转义字符将失效. 因为android已经在传递时做了手脚.

intent.putExtra(EXTRA_OBJECT,People);

比如传递一个People对象, 它有一个详细描述这个People的成员变量Description,
而这个Description成员, 是包含了”\n”转义字符的字符串,那么它在传递的时候,
它的转义字符”\n”已经变成”\\n“了,
所以, 我们要做的是,在对象传递完之后, 把它转换过来.

People people= (People) intent.getSerializableExtra(EXTRA_OBJECT);
String temp = people.getDescription().replace("\\n", "\n");
people.setDescription(temp);

这样一来, 再放到TextView上,就可以正常显示换行了。

转载请注明:Android开发中文站 » Android 换行符(\n) 在TextView中显示不正常的问题


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK