Very simple so straight to the point.
BAD:
In your xmls
- <Button android:id="@+id/buy_button" android:text="Buy Me" />
In your java code
- myButton.setText("Second Button");
GOOD:
Define your strings in strings.xml (You can name it anything) and place it in ‘res/values’ folder
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="buy_button">Buy</string>
</resources>
and then
- <Button android:id="@+id/buy_button" android:text="@string/buy_button" />
- myButton.setText(this.getString(R.string.buy_button));
Syntax for using a ‘resource’ in a xml or code is :
package.R.resource_type.resource_name
and
@[package:]resource_type/resource_name
NOTE: package here does not mean ‘java package’ but package == application, so if you are accessing a resource which is defined in your own app you can skip it. Thats why we use @strings/name or directly R.strings.name. Similarly to use resources defined by android we will use @android:string/name or android.R.string.name
For converting R.string.id to String you can either use getString(int) or getString(int, Object…) for adding dynamic values.
May 28th, 2010 on 2:10 AM
Very useful text
Just a tip for the ones who came here looking for the same as me, and giving an example of what’s written above: strings like android.R.strings.yes or android.R.strings.no can be put into the XML files using android:text=”@android:string/yes” and android:text=”@android:string/no”
July 28th, 2010 on 1:11 AM
Hi Amit,
I am retrieving a string which is stored in the resource file as below.
String res = this.getResources().getText(R.string.celsiusfahrenheit)
My question is: In my code, i want to dynamically substitute the value “celsiusfarrenheit” because I built this value dynamically.
basically can I do something like getText(“R.string.”+dynamicvalue) ? so that this still retrieves value from resource file
thx
vinod