Android textview not supporting line break - android

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!

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

For line break you use set text view in xml layout this way.
Now is the time \r\n for all good men to \r\n come to the aid of their \r\n party

I also had this problem and I found a really SIMPLE SOLUTION, if setting the text from an XML resources (I know this is not the same as OP, but its worth to know it)
There is no need to add line breaks manually, just add the text as it is BUT quoted.
<string name="test_string">"1. First
2. Second Line
3. Third Line"</string>

try this
fireBody.setText(Html.fromHtml("testing<br>line<\br>")
your server need to send FirstLine<br>lineAfterLineBreak<\br>

To force a line break through the XML of your textview, you need to use \r\n instead of just \n.
So, now your code in the XML becomes
android:text="Now is the time \r\n for all good men to \r\n come to the aid of their \r\n party"
Or if you want to do it programatically, then in your java code :
fireBody.setText("Now is the time \r\n for all good men to \r\n come to the aid of their \r\n party");
You can also declare the text as a string resource value, like this :
<string name="sample_string">"some test line 1 \n some test line 2"</string>
Another easy way to do it would be to change the default attribute of the TextView in your xml file.
<TextView
android:id="#+id/tvContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
/>
And then use, textView.setText("First line \nSecond line \nThird line");

I just Use This and now its Work fine for me
message =message.replace("\n","\r\\n");

Related

JSON string to TextView newline

First of all, I have gone through questions similar to the problem I am facing and those solutions are not working for me.
I have a TextView field on my Android app which is supposed to display multiple paragraphs i.e multiple new lines. I am getting this string from a database present in my online server as a JSON.
The text contains \n in it and I am expecting it to create new lines once it is received by the app. But it displays the whole text without any breaks along with "\n" character.
Below is the text present in my database.
First line. \nSecond line. \nThird line.
JSON string received by me inside the app.
{
"server_response": [{
"news_expand": "First line. \\nSecond line. \\nThird line."
}]
}
Code to extract string from JSON. I have left out the code to get get JSONArray and JSONObject for simplicity.
na_expand = gna_jo.getString("news_expand");
String extracted from the JSON. Got this by printing the na_expand string.
First line. \nSecond line. \nThird line.
Code to display the text in the TextView. Note the below 'na_expand' is an SparseArray present in a different activity hence the 'get(position)' code.
art_expand.setText(na_expand.get(position));
Below is the text I get on the emulator.
First line. \nSecond line. \nThird line.
What am I doing wrong here?
I think you should replace \n with \n in your string before setting test to your textview same below
b= b.replaceAll("\\n","\n");
So I found a workaround to the problem. As I was not sure where the issue was happening with \n, I modified my text present in the database to have a symbol other than \n. For eg: ~
First line.~Second line.~Third line.
You can use a website like this - https://www.gillmeister-software.com/online-tools/text/remove-line-breaks.aspx to replace the line breaks with any symbol you want.
Next, I used the StringSplitter class to break the string received in JSON and then again join it together with \n.
String joined;
String expand_temp = na_expand.get(position);
TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter('~');
splitter.setString(expand_temp);
StringBuilder stringBuilder = new StringBuilder();
for (String s_temp : splitter) {
stringBuilder.append(s_temp + "\n");
}
joined = stringBuilder.toString().trim();
This worked! I used this string in setText.
art_expand.setText(joined);
Try below code
myTextView.setText(Html.fromHtml("yourString with additional html tags"));
It will resolve all the html tags accordingly and effects of the tags will be reflected as well.
NOte: For devices greater than Nougat use below code
myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
Hope that helps
The \ character is an escape character in JSON. So, when you get \\n, it actually means \n, not the newline character, which should have been just \n. So what you see is an expected behaviour. The JSON you get should have ideally been:
{
"server_response": [{
"news_expand": "First line. \nSecond line. \nThird line."
}]
}
Get your server to respond properly, otherwise you'll have to strip the unnecessary \.
Do you haveandroid:singleLine="true" on your TextView? If yes it will ignore the \n and will place the text in a single line.
You can just add replaceAll("\\n","\n") when you set value to your art_expand EditText. It should be:
art_expand.setText(na_expand.get(position).replaceAll("\\n","\n"));

\n not breaking lines in Java

I use a google api to generate a QR code from some data. It should be represent a VCARD format.
I call this url.
When i read the QR code, i nicely got back all the information i added to the link, except one little error.
The line sperators not working.
I got back this in Java (Android):
BEGIN:VCARD\nVERSION:2.1\nFN:Adam Varhegyi\nN:Adam;Varhegyi\nEMAIL:somemai#address.com\nTEL:1234567\nINTERNET:;\n\nORG:Mycompanyname\nEND:VCARD
Instead of this: (\n = linebreaks)
BEGIN:VCARD\nVERSION:2.1
FN:Adam Varhegyi
N:Adam;Varhegyi
EMAIL:somemai#address.com
TEL:1234567
INTERNET:;
ORG:Mycompanyname
END:VCARD
I tryed to work it arround with using a Scanner like this:
Scanner sc = new Scanner(myVCardStringInputFromQrCode);
sc.useDelimiter("\n");
while(sc.hasNext()){
String str = sc.next();
Log.i("VCARD LINE: ", str);
}
And this method only gives back 1 line! It is also ignores the "\n" marks.
Edit:
I also tried to use System.getProperty("line.separator") , but no use.
Edit part 2:
if(myVCardStringInputFromQrCode.contains("\n")){
Log.i("Found linebreak", "TRUE");
}
else{
Log.i("Found linebreak", "FALSE");
}
This code gives me back "FALSE" - Java says it is not contains "\n" when i clearly see it is.
Anybody know whats happening here?
Edit part 3:
The correct answer was deleted for some reason so i cannot mark it as "answer".
The solution was "\\n" instead of "\n" and it is working.
you can use System.getProperty("line.separator")
The \n you are seeing is not an actual line break. It is an escaped line break (a backslash, followed by an "n" character).
Try replacing all occurrences of this with an actual line break. Note that you should use the \r\n newline sequence because this is the newline sequence that vCards are supposed to use according to the specs.
myVCardStringInputFromQrCode = myVCardStringInputFromQrCode.replace("\\n", "\r\n");
Remember to pass \\n into the first argument and not \n. You need two backslashes in order to get a literal backslash.
\r\n instead of \n always worked for me.

How to edit multiline strings in Android strings.xml file?

I have several cases where my string in strings.xml is quite long and has multiple lines done with \n.
Editing however is quite annoying since it is a long line in Eclipse.
Is there a better way to edit this so it looks like it will be presented later in the textview, ie the line breaks as line breaks and the text in multiline edit mode?
Two possibilities:
1. Use the Source, Luke
XML allows literal newline characters in strings:
<string name="breakfast">eggs
and
spam</string>
You just have to edit the XML code instead of using the nifty Eclipse GUI
2. Use actual text files
Everything inside the assets directory is available as a input stream from the application code.
You can access those file input streams of assets with AssetManager.open(), a AssetManager instance with Resources.getAssets(), and… you know what, here’s the Java-typical enormously verbose code for such a simple task:
View view;
//before calling the following, get your main
//View from somewhere and assign it to "view"
String getAsset(String fileName) throws IOException {
AssetManager am = view.getContext().getResources().getAssets();
InputStream is = am.open(fileName, AssetManager.ACCESS_BUFFER);
return new Scanner(is).useDelimiter("\\Z").next();
}
the use of Scanner is obviously a shortcut m(
Sure, you could put newlines into the XML, but that won't give you line breaks. In strings.xml, as in all XML files, Newlines in string content are converted to spaces. Therefore, the declaration
<string name="breakfast">eggs
and
spam</string>
will be rendered as
eggs and spam
in a TextView. Fortunately, there's a simple way to have newlines in the source and in the output - use \n for your intended output newlines, and escape the real newlines in the source. The above declaration becomes
<string name="breakfast">eggs\n
and\n
spam</string>
which is rendered as
eggs
and
spam
For anyone looking for a working solution that allows the XML String content to have multiple lines for maintainability and render those multiple lines in TextView outputs, simply put a \n at the beginning of the new line... not at the end of the previous line. As already mentioned, one or more new lines in the XML resource content is converted to one single empty space. Leading, trailing and multiple empty spaces are ignored. The idea is to put that empty space at the end of the previous line and put the \n at the beginning of the next line of content. Here is an XML String example:
<string name="myString">
This is a sentence on line one.
\nThis is a sentence on line two.
\nThis is a partial sentence on line three of the XML
that will be continued on line four of the XML but will be rendered completely on line three of the TextView.
\n\nThis is a sentence on line five that skips an extra line.
</string>
This is rendered in the Text View as:
This is a sentence on line one.
This is a sentence on line two.
This is a partial sentence on line three of the XML that will be continued on line four of the XML but will be rendered completely on line three of the TextView.
This is a sentence on line five that skips an extra line.
You may easily use "" and write any word even from other languages with out error:
<string name="Hello">"Hello
world!
سلام
دنیا!"
</string>

TextView carriage return not working

I am reading a string from an xml file stored on the sdcard that has some carriage returns stored with the "\n" escape sequence. Such as
<string mystring="Line1\nLine2">
But when I display the text in the emulator, the \n is showing up instead of making a newline. I am not doing anything unusual with the text--just reading it with a SAXParser and then adding it to a textview. Is there a setting I need to check to make sure newlines are rendered correctly? Do I need to store the carriage returns differently in the xml file?
I have also tried \r\n and that doesn't work either.
When I debug, I can see that an extra \ is placed in front of the existing \
I see that in my SAX startElement method, the line
String s = atts.getValue("mystring");
assigns "Line1\nLine2" to s, so the problem is with the SAXParser.
works very well in the middle of a quoted textview. I'd like to add that in Eclipses' graphic viewer it puts in an extra space (like it is double spaced). When it is compiled however and you run it on the emulator or a device, you only have the carriage return. So, trust MrGibbage and you'll save yourself some time.
\n is actually a line feed character, while carriage return is \r. Try using both together, e.g. \r\n.
More info about newline.
For handling the whitespace with SAX take a look at ignorableWhitespace(..) method.
Well, I figured out an answer. I had to store the newlines in my xml file ampersand-hash-x-A-semicolon
Use a
where you need the carraige return.

How to add a line break in an Android TextView?

I am trying to add a line break in the TextView.
I tried suggested \n but that does nothing. Here is how I set my texts.
TextView txtSubTitle = (TextView)findViewById(r.id.txtSubTitle);
txtSubTitle.setText(Html.fromHtml(getResources().getString(R.string.sample_string)));
This is my String: <string name="sample_string">some test line 1 \n some test line 2</string>
It should show like so:
some test line 1
some test line 2
But it shows like so: some test line 1 some test line 2.
Am I missing something?
\n works for me, like this:
<TextView android:text="First line\nNext line"
ok figured it out:
<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>
so wrap in CDATA is necessary and breaks added inside as html tags
Android version 1.6 does not recognize \r\n.
Instead, use: System.getProperty("line.separator")
String s = "Line 1"
+ System.getProperty("line.separator")
+ "Line 2"
+ System.getProperty("line.separator");
Linebreaks (\n) only work if you put your string resource value in quotes like this:
<string name="sample_string">"some test line 1 \n some test line 2"</string>
It won't do linebreaks if you put it without quotes like this:
<string name="sample_string">some test line 1 \n some test line 2</string>
yes, it's that easy.
Tried all the above, did some research of my own resulting in the following solution for rendering linefeed escape chars:
string = string.replace("\\\n", System.getProperty("line.separator"));
Using the replace method you need to filter escaped linefeeds (e.g. '\\n')
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 formatted data.
Cheers :D
There are two ways around this.
If you use your string as a raw string, you need to use the newline
character. If you use it as html, e.g. by parsing it with Html.fromString,
the second variant is better.
1) Newline character \n
<string name="sample">This\nis a sample</string>
2) Html newline tag <br> or <br />
<string name="sample">This<br>is a sample</string>
This worked for me
android:text="First \n Second"
This worked for me, maybe someone will find out this helpful:
TextView textField = (TextView) findViewById(R.id.textview1);
textField.setText("First line of text" + System.getProperty("line.separator") + "Linija 2");
If you're using XML to declare your TextView use android:singleLine = "false" or in Java, use txtSubTitle.setSingleLine(false);
Used Android Studio 0.8.9. The only way worked for me is using \n.
Neither wrapping with CDATA nor <br> or <br /> worked.
I use the following:
YOUR_TEXTVIEW.setText("Got some text \n another line");
very easy : use "\n"
String aString1 = "abcd";
String aString2 = "1234";
mSomeTextView.setText(aString1 + "\n" + aString2);
\n corresponds to ASCII char 0xA, which is 'LF' or line feed
\r corresponds to ASCII char 0xD, which is 'CR' or carriage return
this dates back from the very first typewriters, where you could choose to do only a line feed (and type just a line lower), or a line feed + carriage return (which also moves to the beginning of a line)
on Android / java the \n corresponds to a carriage return + line feed, as you would otherwise just 'overwrite' the same line
As I know in the previous version of android studio uses separate lines " \n " code. But new one (4.1.2) uses "<br/" to separate lines. For example -
Old one:
<string name="string_name">Sample text 1 \n Sample text 2 </string>
New one:
<string name="string_name">Sample text 1 <br/> Sample text 2 </string>
Also you can add "<br/>" instead of \n.
It's HTML escaped code for <br/>
And then you can add text to TexView:
articleTextView.setText(Html.fromHtml(textForTextView));
Try to double-check your localizations.
Possible, you trying to edit one file (localization), but actually program using another, just like in my case. The default system language is russian, while I trying to edit english localization.
In my case, working solution is to use "\n" as line separator:
<string name="string_one">line one.
\nline two;
\nline three.</string>
You could also use the String-Editor of Android Studio, it automatically generates line brakes and stuff like that...
As Html.fromHtml deprecated I simply I used this code to get String2 in next line.
textView.setText(fromHtml("String1 <br/> String2"));
.
#SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
The most easy way to do it is to go to values/strings (in your resource folder)
Declare a string there:
<string name="example_string">Line 1\Line2\Line n</string>
And in your specific xml file just call the string like
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/example_string" />
I found another method:
Is necessary to add the "android:maxWidth="40dp"" attribute.
Of course, it may not work perfectly, but it gives a line break.
\n was not working for me. I was able to fix the issue by changing the xml to text and building the textview text property like below.
android:text="Line 1
Line 2
Line 3
DoubleSpace"
Hopefully This helps those who have said that \n did not work for them.
I'm reading my text from a file, so I took a slightly different approach, since adding \n to the file resulted in \n appearing in the text.
final TextView textView = (TextView) findViewById(R.id.warm_up_view);
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.warm_up_file));
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine());
sb.append("\n");
}
textView.setText(sb.toString());
In my case, I solved this problem by adding the following:
android:inputType="textMultiLine"
Maybe you are able to put the lf into the text, but it doesn't display? Make sure you have enough height for the control. For example:
Correct:
android:layout_height="wrap_content"
May be wrong:
android:layout_height="10dp"
I feel like a more complete answer is needed to describe how this works more thoroughly.
Firstly, if you need advanced formatting, check the manual on how to use HTML in string resources.
Then you can use <br/>, etc. However, this requires setting the text using code.
If it's just plain text, there are many ways to escape a newline character (LF) in static string resources.
Enclosing the string in double quotes
The cleanest way is to enclose the string in double quotes.
This will make it so whitespace is interpreted exactly as it appears, not collapsed.
Then you can simply use newline normally in this method (don't use indentation).
<string name="str1">"Line 1.
Line 2.
Line 3."</string>
Note that some characters require special escaping in this mode (such as \").
The escape sequences below also work in quoted mode.
When using a single-line in XML to represent multi-line strings
The most elegant way to escape the newline in XML is with its code point (10 or 0xA in hex) by using its XML/HTML entity
or
. This is the XML way to escape any character.
However, this seems to work only in quoted mode.
Another method is to simply use \n, though it negatively affects legibility, in my opinion (since it's not a special escape sequence in XML, Android Studio doesn't highlight it).
<string name="str1">"Line 1.
Line 2.
Line 3."</string>
<string name="str1">"Line 1.\nLine 2.\nLine 3."</string>
<string name="str1">Line 1.\nLine 2.\nLine 3.</string>
Do not include a newline or any whitespace after any of these escape sequences, since that will be interpreted as extra space.
I would recommend querying the line.separator property, and using that whenever you want to add a line break.
Here is some sample code:
TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+" line2" );

Categories

Resources