我正在通过编程方式创建一个自定义视图,用于显示从XML文件解析出的文本。这段文本很长,并且包含“/n”字符以强制换行。但是,某种原因导致文本视图将/n显示出来,而没有任何换行符。以下是我的代码:
// get the first section body
Object body1 = tempDict.get("FIRE");
String fireText = body1.toString();
// create the section body
TextView fireBody = new TextView(getActivity());
fireBody.setTextColor(getResources().getColor(R.color.black));
fireBody.setText(fireText);
fireBody.setTextSize(14);
fireBody.setSingleLine(false);
fireBody.setMaxLines(20);
fireBody.setBackgroundColor(getResources().getColor(R.color.white));
// set the margins and add to view
layoutParams.setMargins(10, 0, 10, 0);
childView.addView(fireBody,layoutParams);
XML文件中的文本如下:
Now is the time /n for all good men to /n come to the aid of their /n party
它应该显示如下;Now is the time
for all good men to
come to the aid of their
party
我是否遗漏了某些设置?
更新
\r\n 如果我将其硬编码到视图中,它可以正常工作。例如:
String fireText = "Now is the time \r\n for all good men \r\n to come to the aid";
如果我硬编码,实际上 "\n" 也可以工作:
String fireText = "Line one\nLine two\nLine three";
顺便提一下
System.getProperty("line.separator");
这将返回一个字符串"/n",因此无需转换为"/r/n"。
不幸的是,我的数据源来自解析并存储在哈希映射表中的XML文件。我尝试了以下方法:
String fireText = body1.toString().replaceAll("\n", "\r\n");
\n未被替换为\r\n。这可能是因为我正在将对象转换为字符串吗?