Android textview不支持换行符

wyo*_*bum 19 android textview android-xml

我正在以编程方式创建一个自定义视图,显示从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);
Run Code Online (Sandbox Code Playgroud)

XML文件中的文本是这样的:

Now is the time /n for all good men to /n come to the aid of their /n party
Run Code Online (Sandbox Code Playgroud)

它应该如此显示;

Now is the time
for all good men to
come to the aid of their
party
Run Code Online (Sandbox Code Playgroud)

是否有我失踪的场景?

UPDATE

\ r \n如果我将其硬编码到我的视图中,则有效.即:

String fireText = "Now is the time \r\n for all good men \r\n to come to the aid";
Run Code Online (Sandbox Code Playgroud)

实际上\n如果我硬代码它也有效:

String fireText = "Line one\nLine two\nLine three";
Run Code Online (Sandbox Code Playgroud)

FYI

System.getProperty("line.separator");
Run Code Online (Sandbox Code Playgroud)

这将返回一个"/ n"字符串,因此无需转换为"/ r/n".

不幸的是,我的数据源自一个XML文件,该文件被解析并存储在一个hashmap中.我尝试了以下方法:

String fireText = body1.toString().replaceAll("\n", "\r\n");
Run Code Online (Sandbox Code Playgroud)

\n没有被\ r \n取代.可能是因为我正在从一个对象转换为String吗?

Rob*_*Rob 53

我一直有在精确的下同样的问题完全一样的情况下.解决方案相当直接.

当你考虑它时,由于textview小部件正在显示带有文字"\n"值的文本,那么它所给出的字符串必须存储每个"\n",如"\\n".因此,当读取并存储XML字符串时,所有出现的"\n"都将被转义,以将该文本保存为文本文本.

无论如何,你需要做的就是:

fireBody.setText(fireText.replace("\\n", "\n"));
Run Code Online (Sandbox Code Playgroud)

适合我!

  • ReplaceAll() 使用正则表达式作为第一个参数,replace() 使用普通字符串 (2认同)

小智 5

尝试了以上所有方法,我自己做了一些研究,得出了以下用于渲染换行符转义字符的解决方案:

string = string.replace("\\\n", System.getProperty("line.separator"));
Run Code Online (Sandbox Code Playgroud)

1) 使用您需要过滤转义换行符的替换方法(例如'\\n')

2) 只有这样,换行符 '\n' 转义字符的每个实例才会被渲染到实际的换行符中

在本示例中,我使用了带有 JSON 格式数据的 Google Apps Scripting noSQL 数据库 (ScriptDb)。

干杯:D