【发布时间】:2013-07-18 18:08:00
【问题描述】:
我想知道如何在strings.xml 中创建一个字符串数组,以及如何在java 代码中访问它。我需要这个才能使用 setText()。请帮忙。
【问题讨论】:
标签: java android xml arrays string
我想知道如何在strings.xml 中创建一个字符串数组,以及如何在java 代码中访问它。我需要这个才能使用 setText()。请帮忙。
【问题讨论】:
标签: java android xml arrays string
字符串.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array"> // name of the string array
<item>Mercury</item> // items
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
</string-array>
</resources>
在你的活动课上。
Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);
or
String[] planets = getResources().getStringArray(R.array.planets_array);
getResource 需要活动上下文。如果它在非活动类中,您将需要可以传递给非活动类构造函数的活动上下文。
来源@
http://developer.android.com/guide/topics/resources/string-resource.html#StringArray
编辑:
new CustomAdapter(ActivityName.this);
然后
class CustomAdapter extends BaseAdapter
{
Context mContext;
public CustomAdapter(Context context)
{
mContext = context;
}
...// rest of the code
}
使用mContext.getResources()
【讨论】:
您在 strings.xml 中创建一个字符串数组,如下所示:
<string-array name="my_string_array">
<item>first string</item>
<item>second</item>
</string-array>
然后您可以通过以下方式访问它:
String[] str = getResources().getStringArray(R.array.my_string_array);
【讨论】: