简体   繁体   中英

Access string.xml Resource File from Java Android Code

如何从Android Activity class访问res/values/string.xml资源文件中的res/values/string.xml

Well you can get String using,

getString(R.string.app_name);

And, you can get string-array using

String arr[] = getResources().getStringArray(R.array.planet);
for (int i = 0; i < arr.length; i++) {
        Toast.makeText(getBaseContext(),arr[i], Toast.LENGTH_LONG).show();  
}

strings.xml:

<string name="some_text">Some Text</string>

Activity:

getString(R.string.some_text);

If getString(R.string.app_name); isn't working for you, you can pass context like this:

context.getString(R.string.app_name);

Put this code in res/values/string.xml

<string-array name="planet"> 
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
</string-array>

This code to be placed in res/layout/main.xml and remove default widgets present in main.xml .

<ListView android:id="@+id/planet"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:entries="@array/planet"/>
</LinearLayout>

If you have the context of Activity, go with:

getString(R.string.app_name);

If you don't have the context, try below, you can get the context from activity using Constructor .

mContext.getString(R.string.app_name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM