How to use escape characters in XML - android

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.

Related

how to set apostrophe in TextView programming

TextView.setText(String with ') , i wanna set a text to the text view but this text keep coming uncompleted in case it has Space or apostrophe
i have tried to use
String SomeString="MacDonald's";
or
SomeString="Fast Food";
and i tried the following
HTML.Fromhtml(SomeString).tostring()
and
SomeString.replace("'","\\\'")
but with no good result
the Result always
MacDon
Fast
any good ideas ?!
Make sure your apostrophe is ' and not special one like ‘
From android developer documentation
you can set apostrophe from XML
Single quote (')
Any of the following:
1. &apos;
2. \'
3. Enclose the entire string in double quotes ("This'll work", for example)
Sample
1. <string name="travelers_details">Traveler&apos;s Information</string>
2. <string name="travelers_details">Traveler\'s Information</string>
Apastrophe cannot be directly displayed. Instead of directly placing Apastrophe use the below when you encounter the apastrophe as below:
if (YourString.contains("'")) {
YourString= YourString.replaceAll("'", "\'");
}
This will help you
I believe, calling yourTextView.setText("MacDonald's"); will simply set MacDonald's inside your TextView. You don't need anything fancy to get it printed.

Android: How store url in string.xml resource file?

I'm trying to store a fully qualified url, with also query params:
www.miosito.net?prova&reg=bis
but it's causing a problem because &reg is similar to ® entity and android tell me that and html entity is not well written.
I need this because every locale uses a fully different set of url query param.
I tried with [[CDATA[.. ]] but this syntax disliked by xml parser.
The problem is not with &req but with & itself. For XML/HTML you would have to use & entity (or &), but for URLs you should rather URL-encode (see docs) strings, and in that case said & should be replaced with %26. So your final string should look like:
www.miosito.net?prova%26reg=bis
Store it like this:
<string name="my_url">"www.miosito.net?prova&reg=bis"</string>
Where & is the XML equivelant of the ampersand symbol &.
Percent encoding may do the trick: http://en.wikipedia.org/wiki/Percent-encoding
You'll basically have something like this: www.miosito.net?prova%26reg=bis
You can enclose your url in double quotes, something like :
<string name="my_url">"www.miosito.net?prova&reg=bis"</string>
This is a recommended way to enclose string resources in Android.
Update 1 : Have a look at the following link for more info :
http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
Update 2:
#WebnetMobile.com : Correct, indeed :)
'&' is being treated a special character by xml and enclosing in quotes doesn't work. I tried out
www.miosito.net?prova%26reg=bis
and it didn't work out either. I even tried enclosing it in quotes but still didn't work. Am I missing something ?
Meanwhile, the following does work :
<string name="my_url">www.miosito.net%1$sprova%2$sreg=bis</string>
and then in code :
Resources resources=getResources();
String url=String.format(resources.getString(R.string.my_url),"?","&") ;
The '%1$s' and '%2$s' are format specifiers, much like what is used in printf in C. '%1$s' is for strings, '%2$d' is for decimal numbers and so on.

Android how to add the # sign as text

hi I'm just creating a header for a app that uses twitter and just wanting to know how to show the # as text i put it in a string and it doesn't like it
<string name="twit">#evosdfresh</string>
then i call this string it doesn't work if i remove the # it works so its the # thats throwing it off
Try replacing the # char with its utf-8 xml decimal representation: #
EDIT: given the xml entity does not work, use the unicode definition: \u0040
If you have the # as the first character of the string, then you need to escape it with a backslash, e.g.
<string name="twit">\#evosdfresh</string>
If it's in the middle of the string you don't need the backslash.
Try # instead of #. If that doesn't work, you could also try escaping it, with 2 #'s instead of 1, or a backslash before it. ##evosdfresh or \#evosdfresh
My idea is to replace it with an #. Tell me if it works, I'd be interested to know, too ;)

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" );

How to keep the spaces at the end and/or at the beginning of a String?

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 &amp ; 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);

Categories

Resources