I'm creating a custom view programmatically that is displaying text that is parsed from an XML file. The text is long and contains the "/n" character for force line breaks. For some reason, the text view is displaying the /n and there isn't any line breaks. Here is my code:
// 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);
The text from the XML file is like this:
Now is the time /n for all good men to /n come to the aid of their /n party
It should display as such;
Now is the time
for all good men to
come to the aid of their
party
Is there are setting that I'm missing?
UPDATE
\r\n works if I hard code it into my view. ie:
String fireText = "Now is the time \r\n for all good men \r\n to come to the aid";
Actually \n also works if i hard code it:
String fireText = "Line one\nLine two\nLine three";
FYI
System.getProperty("line.separator");
this returns a string of "/n" so there is no need to convert to "/r/n".
Unfortunately, my data originates in a XML file that is parsed and stored in a hashmap. I tried the following:
String fireText = body1.toString().replaceAll("\n", "\r\n");
The \n is not getting replaced with \r\n. Could it be because I'm converting from an object to String?
I've been having the exact same problem under the exact same circumstances. The solution is fairly straight forward.
When you think about it, since the textview widget is displaying the text with the literal "\n" values, then the string that it is being given must be storing each "\n" like "\\n". So, when your XML string is read and stored, all occurrences of "\n" are being escaped to preserve that text as literal text.
Anyway, all you need to do is:
fireBody.setText(fireText.replace("\\n", "\n"));
Works for me!