【问题标题】:String Array in res/values/strings.xml [closed]res/values/strings.xml 中的字符串数组 [关闭]
【发布时间】:2013-07-18 18:08:00
【问题描述】:

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

【问题讨论】:

    标签: java android xml arrays string


    【解决方案1】:

    字符串.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()

    【讨论】:

    • 感谢您的回答。我需要更多的东西。我想在不支持 getResources(); 的 BaseAdapter 中执行此操作。我这样做的方法是调用 MainActivity 中的 getResourses,然后将带有 SharedPreferences 的数组发送到 BaseAdapter 。有没有办法直接在 BaseAdapter 中做到这一点?
    • @mremremre1 检查编辑
    【解决方案2】:

    您在 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);
    

    【讨论】:

    • 感谢您的回答。我需要更多的东西。我想在不支持 getResources(); 的 BaseAdapter 中执行此操作。我这样做的方法是调用 MainActivity 中的 getResourses,然后将带有 SharedPreferences 的数组发送到 BaseAdapter 。有没有办法直接在 BaseAdapter 中做到这一点?
    • 是的,使用你的 Activity 的上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多