Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android reference string in string.xml

Is it possible to reference a string in strings.xml

Eg:

<string name="application_name">@string/first_name Browser</string>
<string name="first_name">Chrome</string>

Where depending on requirements, i can switch the value of first_name to "Chrome", "Firefox" or "Opera".

like image 511
Vinoth Avatar asked Apr 12 '12 10:04

Vinoth


People also ask

What is string xml file in Android?

String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.

How do you get string resources?

android:text="@string/hello" /> String string = getString (R. string. hello); You can use either getString(int) or getText(int) to retrieve a string.

In which folder can you find the string resource file strings xml?

You can find strings. xml file inside res folder under values as shown below.

Why should you use string resources instead of hard coded strings in your apps?

It is not good practice to hard code strings into your layout files. You should add them to a string resource file and then reference them from your layout. This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings.


1 Answers

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");
like image 70
Mohammed Azharuddin Shaikh Avatar answered Sep 17 '22 21:09

Mohammed Azharuddin Shaikh