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
August 9th, 2010 on 6:10 AM
use the getIdentifier() method to get the resource id, then you can use getText( resId );
August 4th, 2011 on 1:09 AM
all those people writing good information are really cool
August 4th, 2011 on 2:43 AM
thanks, though i might try another twist on it, but again, i do appreciate the information.
January 31st, 2012 on 5:17 AM
Wonderful goods from you, man. I have understand your stuff previous to and you are just extremely excellent. I actually like what you’ve acquired here, certainly like what you are saying and the way in which you say it. You make it enjoyable and you still take care of to keep it wise. I can not wait to read far more from you. This is really a terrific website.
February 8th, 2012 on 12:20 AM
I bet you have no idea what I would give to be able to read more such good blogs.