[英]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, 那么你可以使用String,
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: strings.xml中:
<string name="some_text">Some Text</string>
Activity: 活动:
getString(R.string.some_text);
If getString(R.string.app_name); 如果是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
将此代码放在
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
. 这个代码被放置在
res/layout/main.xml
和除去存在于默认窗口小部件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: 如果您有Activity的上下文,请使用:
getString(R.string.app_name);
If you don't have the context, try below, you can get the context from activity using Constructor
. 如果您没有上下文,请尝试下面的操作,您可以使用
Constructor
从活动中获取上下文。
mContext.getString(R.string.app_name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.