Use string with arguments with tools:text - android

I have a string with arguments (for example <string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>). I know, that I can use it at my code with String.format(res.getString(R.string.welcome_messages), username, mailCount); and I will get a full message with username and count. But can I preview it in .xml layout, using tools:text? or any other tools instrument?

No you can't.
According to the documentation of TextView and the Tools-Attribute there is no way to replace the String placeholders in XML.
I was researching this a while ago and ended up hard-coding the text via tools:text. As this only affects design previews I think that hardcoding the text is okay in this case.

Related

Android what is the formatted flag for string resource means?

Basically question in the title.
I have seen several examples when people apply formatted flag to string resource, but can't find any official explanation, what this flag does.
There isn't any format documentation on the flag in Android docs, but the flag is commonly used to indicate a string that should be formatted before being shown to the user.
The Android docs show an example of how to do this.
Per the example at the link, you may have a string resource named welcome_messages,
<string name="welcome_messages" formatted="true">Hello, %1$s! You have %2$d new messages.</string>
that allows you to format a welcome message with a custom name and number of messages. You would use this string as follows
String text = getString(R.string.welcome_messages, username, mailCount);
The formatted flag helps distinguish strings that need to be formatted in this matter before being shown to the user.

how can I solve this error string xliff?

I have this string:
<string name="order_summary_name">Name: <xliff:g id="name" example="Thomas">%s</xliff:g></string>
using it in this format:
priceMessage=getString(R.string.order_summary_name,name);
and I keep getting an error that says: Format string 'order_summary_name' is not a valid string.
I cant find the mistake,what should I do ???
Store your styled text resource as an HTML-escaped string:
<resources>
<string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string>
</resources>
In this formatted string, a element is added. Notice that the opening bracket is HTML-escaped, using the < notation.
Then format the string as usual, but also call fromHtml(String) to convert the HTML text into styled text:
String text = getString(R.string.welcome_messages, username, mailCount);
String styledText = Html.fromHtml(text);
(or)
String styledText = Html.fromHtml(R.string.order_summary_name,name);
https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
The id attribute is just used to identify what the substitution parameter represents (in your case, it represents the quantity). It's as you said, a note, and not actually used programmatically.
That said, in Android Studio, if you have Code Folding enabled for strings, it will substitute in the ID when it shows the collapsed string. You'd see something like this:
Try this.
mTextView.setText(getString(R.string.order_summary_name, "Thoma"));

Android Charsequence - replacing text

Due to HTML usage within a string resource, I can't convert this to string from a charsequence (I will lose the formatting otherwise).
<string name="exponent_key">x<sup><small>y</small></sup>/string>
After using getString() I want to replace the 'y' with 'other stuff' but how do you do that? It seems like a simple question but for some reason I can't find anything about it.
Edit: Now that I think about it, can I convert the charsequence to a string that contains the HTML code, and then convert it back to a charsequence later?
Edit: Forgot to mention that the string gets set to a button title, and then retrieved (where it is then used).
There is. Create a function where, as a parameter, you take a string that needs to be formatted. And in function, you just take it through itterator, and after that Html.fromHtml()
in your string.xml
<string name="exponent_key">x<sup><small>%1$d</small></sup></string>
in your code
textView.setText(getString(R.string.exponent_key,2))
Let's break down your question in multiple steps:
Replacing the y with "other stuff" can be done like this:
String.format("%1$", "otherStuff");
If you use getString(), you can do the same thing like that:
<string name="exponent_key">%1$</string>
---
String string = getString(R.string.exponent_key, "otherStuff");
For more than one element, do this way:
you can do that like this:
<string name="string_name">%1$ : %2$</string>
---
getString(R.string.string_name, new String[]{"hello", "world"});
In XML you cannot nest HTML code, since HTML is another type of XML and the parser messes up and cannot recognize what tags are for Android and what are for HTML. But.. there's a trick. You can do that in this way:
<string name="exponent_key"><![CDATA[x<sup><small>%1$</small>/sup>]]></string>
So, with the string above in your XML, just use and you're fine:
getString(R.string.exponent_key, "otherStuff");
Note: if you need to show the HTML in a TextView, just use Html.fromHtml:
textView.setText(Html.fromHtml(getString(R.string.exponent_key, "otherStuff")));
Consider the effect you want to achieve.
you can do like this.
SpannableString ss = new SpannableString("2");
// set superscript
ss.setSpan(new SuperscriptSpan(),0,ss.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// set font size
ss.setSpan(new AbsoluteSizeSpan(12,true),0,ss.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.append(ss);

Formatting Strings

People often link the following for explaining formatted strings, Can anyone show me a working example of how to use this?
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
well the name of the string is "welcome_message", for example you want to add that formated text into component, just edit layout.xml, find your component, and set the text on component to use that string
component < ....
android:text="#string/welcome_message
... />

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