Using strings.xml w/ Android
I've looked and tried many things but it seems my App isn't getting the values for strings in strings.xml. It actually seems like it's passing blank. I think there's an issue initializing.
strings.xml
<string name="itb_cityID">2</string>
<string name="itb_city">New York</string>
constants.java excerpt:
public class ConstantData {
public static String cityID="2";
public static String city="New York";
How do I set 开发者_运维问答cityID = R.strings.itb_cityID
and city=itb_city
the correct way?
String yourString = Context.getResources().getString(R.string.your_string);
Note: You can't use Context
statically. If you're inside an Activity, simply use this
or call getResources()
directly. Otherwise you'll need to obtain a handle to your application's context via getApplicationContext()
.
This example could be useful
XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello!</string> </resources>
This layout XML applies a string to a View
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
This application code retrieves a string:
String string = getString(R.string.hello);
You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.
This example is from http://developer.android.com/guide/topics/resources/string-resource.html
Have you checked that the entire project is error free. If it is not there may be an error that is preventing R.java from being updated with your string. You could try to "Clean" you projected from the "Project" menu. That may work. Also, I can't see why you would have to use Context.
, usually you should be able to call getResources().
directly (in some situations even this is unnecessary). A good thing to look for is if the string you have declared in your strings.xml file is recognised as a declared string.
精彩评论