res / values / strings.xml中的字符串数组

时间:2013-07-19 12:43:54

标签: java android xml arrays string

我想知道如何在strings.xml中创建一个字符串数组,以及如何在java代码中访问它。我需要这个才能使用setText()。请帮忙。

2 个答案:

答案 0 :(得分:6)

的strings.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()

答案 1 :(得分:1)

您可以在strings.xml中创建一个String数组,如:

<string-array name="my_string_array">
      <item>first string</item>
      <item>second</item>
</string-array>

然后您可以使用以下内容访问它:

String[] str = getResources().getStringArray(R.array.my_string_array);