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" );
Related
I'm trying to translate my android app from English to Hebrew by adding a strings.xml file to values directory and translating all English strings.
My problem is that adding a line break (\n) to the Hebrew string as i do with my English strings.xml strings doesn't work. An example to an English string with a line break:
<string name="no_group_instructions">You don\'t have a group yet!\n\nPlease choose whether to create a new group, or to join an existing one...</string>
How can i add line breaks to my non-English strings?
EDIT
I eventually did manage to do the line break in the Hebrew string using \n.
I guess that the right-to-left writing, which is not supported well enough in Android Studio, caused the problem in the first place. I solved it by copying the string with the \n's from notepad straight to the strings.xml file, and not wrote it directly in the Android Studio.
I had the same problem. To solve it, just copy-paste "\n" into your string as I did:
<string name="ta_tv_button_text">?היוםn\אכלתn\מה</string>
Make sure you support RTL in both your manifest and the TextView.
I could not copy-paste my string into here (it mixed up the string). I believe it will mix it up again if you try to copy-paste it to your project, so do not copy-paste my string to your project. This is how the string looks like in my project.
You have to use <br /> to break line in xml instead of \n for example :
<string name="no_group_instructions">You don\'t have a group yet!
<br/><br/>Please choose whether to create a new group, or to join an existing one...
</string>
There is a cool way to do this, at runtime.
<string name="title">Testing%sNew Line, stand back!</string>
%s is a string , and be replaced.
Then get it by resources String word = String.format(Locale.English,getString(R.string.title),"\n");
It will load the string then replace then %s with \n
use a blackslash not a forwardslash. "\n"
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">Hello\nWorld!</string>
</resources>
String formattedText = getString(R.string.no_group_instructions);
Spanned result = Html.fromHtml(formattedText);
view.setText(result);
I want to put a Font-Awesome icon inside textview text. After I set the text, android shows me a string sequence instead of font-icon.
My code is:
String formatedSection = formatedSection + sections.get(i).getContent() +getResources().getString(R.string.icon_ref);
I define icon_ref in string.xml as below:
<string name="icon_ref"></string>
I followed these instructions to add font-icon. What am I doing wrong?
If you did step 5 in that short guid your problem seem to forget that there is a diff between java and XML.
In XML you use XML escape (&...;), in Java you'll probably have to use Java escape (\u...). – Biffen May 20 at 10:10
Try to hard code the string into "\uf075" and it would work like a charm.
How can I use escape characters in XML?
The situation is, I am a new android developer, and I need a string which need to be printed in 2 lines (other wise no space). This string is in string.xml file. I need to use /n line break character to break the string, but I don't know how to do it in XML file. Please help.
See reference http://developer.android.com/guide/topics/resources/string-resource.html#String
line break symbol is \n
/n - is wrong.
and you can write it in xml like it is.
Example:
<string name="multiline_text">line 1.\nline2.</string>
I'm not familiar with Android development but have you checked out CDATA? Refer to this link.
Basically, you wrap your string value like so:
<![CDATA[string value]]>
You can use double quotes:
<string name="mystring">"One line\nAnother line"</string>
You can use the character entity
to indicate a linefeed.
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");
I have to concatenate these two strings from my resource/value files:
<string name="Toast_Memory_GameWon_part1">you found ALL PAIRS ! on </string>
<string name="Toast_Memory_GameWon_part2"> flips !</string>
I do it this way :
String message_all_pairs_found = getString(R.string.Toast_Memory_GameWon_part1)+total_flips+getString(R.string.Toast_Memory_GameWon_part2);
Toast.makeText(this, message_all_pairs_found, 1000).show();
But the spaces at the end of the first string and at the beginning of the second string
have disappeared (when the Toast is shown) ...
What should I do ?
I guess the answer is somewhere here in this documentation link
or is it something like using & ; for the "&" character ??
Even if you use string formatting, sometimes you still need white spaces at the beginning or the end of your string. For these cases, neither escaping with \, nor xml:space attribute helps. You must use HTML entity for a whitespace.
Use for non-breakable whitespace.
Use for regular space.
I ran into the same issue. I wanted to leave a blank at the end of a resource string representing an on-screen field name.
I found a solution on this issue report : https://github.com/iBotPeaches/Apktool/issues/124
This is the same idea that Duessi suggests. Insert \u0020 directly in the XML for a blank you would like to preserve.
Example :
<string name="your_id">Score :\u0020</string>
The replacement is done at build time, therefore it will not affect the performance of your game.
This documentation suggests quoting will work:
<string name="my_str_spaces">" Before and after? "</string>
I just use the UTF code for space "\u0020" in the strings.xml file.
<string name="some_string">\u0020The name of my string.\u0020\u0020</string>
works great. (Android loves UTF codes)
This question may be old, but as of now the easiest way to do it is to add quotation marks.
For example:
<string name="Toast_Memory_GameWon_part1">"you found ALL PAIRS ! on "</string>
<string name="Toast_Memory_GameWon_part2">" flips !"</string>
There is possible to space with different widths:
<string name="space_demo">| | | ||</string>
| SPACE | THIN SPACE | HAIR SPACE | no space |
Visualisation:
use "" with the string resource value.
Example :
<string>"value with spaces"</string>
OR
use \u0020 code for spaces.
If you really want to do it the way you were doing then I think you have to tell it that the whitespace is relevant by escaping it:
<string name="Toast_Memory_GameWon_part1">you found ALL PAIRS ! on\ </string>
<string name="Toast_Memory_GameWon_part2">\ flips !</string>
However, I'd use string formatting for this. Something like the following:
<string name="Toast_Memory_GameWon">you found ALL PAIRS ! on %d flips !</string>
then
String message_all_pairs_found = String.format(getString(R.string.Toast_Memory_GameWon), total_flips);
Working well
I'm using \u0020
<string name="hi"> Hi \u0020 </string>
<string name="ten"> \u0020 out of 10 </string>
<string name="youHaveScored">\u0020 you have Scored \u0020</string>
Java file
String finalScore = getString(R.string.hi) +name+ getString(R.string.youHaveScored)+score+ getString(R.string.ten);
Toast.makeText(getApplicationContext(),finalScore,Toast.LENGTH_LONG).show();
Screenshot
here Image of Showing Working of this code
All answers here did not work for me. Instead, to add a space at the end of a string in XML i did this
<string name="more_store">more store<b> </b> </string>
An argument can be made for adding the space programmatically. Since these cases will be often used in concatenations, I decided to stop the madness and just do the old + " " +. These will make sense in most European languages, I would gather.
I've no idea about Android in particular, but this looks like the usual XML whitespace handling - leading and trailing whitespace within an element is generally considered insignificant and removed. Try xml:space:
<string name="Toast_Memory_GameWon_part1" xml:space="preserve">you found ALL PAIRS ! on </string>
<string name="Toast_Memory_GameWon_part2" xml:space="preserve"> flips !</string>
This may not actually answer the question (How to keep whitespaces in XML) but it may solve the underlying problem more gracefully.
Instead of relying only on the XML resources, concatenate using format strings.
So first remove the whitespaces
<string name="Toast_Memory_GameWon_part1">you found ALL PAIRS ! on</string>
<string name="Toast_Memory_GameWon_part2">flips !</string>
And then build your string differently:
String message_all_pairs_found =
String.format(Locale.getDefault(),
"%s %d %s",
getString(R.string.Toast_Memory_GameWon_part1),
total_flips,
getString(R.string.Toast_Memory_GameWon_part2);
Toast.makeText(this, message_all_pairs_found, 1000).show();
There is also the solution of using CDATA. Example:
<string name="test"><![CDATA[Hello world]]></string>
But in general I think \u0020 is good enough.
If you need the space for the purpose of later concatenating it with other strings, then you can use the string formatting approach of adding arguments to your string definition:
<string name="error_">Error: %s</string>
Then for format the string (eg if you have an error returned by the server, otherwise use getString(R.string.string_resource_example)):
String message = context.getString(R.string.error_, "Server error message here")
Which results in:
Error: Server error message here
It does not work with xml:space="preserve"
so I did it the quickest way =>
I simply added a +" "+ where I needed it ...
String message_all_pairs_found = getString(R.string.Toast_Memory_GameWon_part1)+" "+total_flips+" "+getString(R.string.Toast_Memory_GameWon_part2);