Wednesday, 29 July 2015

android strings.xml a string referent another string

The answer is you can reference A string in B string, but B string can not contain other stuffs.

You can connect 2 strings in B. You can not connect A with "xxx" in B string.

A good post from :

You can give the reference of string resource, but limitation are as follows
<string name="first_name">Chrome</string>
<string name="application_name">@string/first_name</string> // gives "Chrome"
<string name="application_name">Chrome @string/first_name</string> // gives "Chrome @string/first_name"
<string name="application_name">@string/first_name Chrome </string> // gives error
If content starts with "@" then Android considers this is a referenced string, see last case which gives an error because Android's tools take @ and the next string to it as the string's reference name, it will try to find a resource called "@string/first_name Chrome" which doesn't exist.
You can use String Format to dynamically assign sub-strings like <string name="application_name">%1$s browser</string>
to use
String text = String.format(res.getString(R.string.application_name), "Chrome");

To connect two string together:

One string, one ""

I think you can't. But you can "format" a string as you like:
<?xml version="1.0" encoding="utf-8"?>
    <string name="button_text">Add item</string>
    <string name="message_text">You don't have any items yet! Add one by pressing the %1$s button.</string>
In the code:
Resources res = getResources();
String text = String.format(res.getString(R.string.message_text),

Two strings.

<string name="title">%1$s test</string>
<string name="title2">%1$s %2$s</string>

<string name="app_name">AppName</string>
<string name="version_name">1.2</string>
And then from Java code do something like:
Resources res = getResources();
String appName = res.getString(R.string.app_name);
String versionName = res.getString(R.string.version_name);

String title = res.getString(R.string.title, appName);
String title2 = res.getString(R.string.title2, appName, versionName); 

No comments:

Post a comment