【问题标题】:Android: How do you access a string-array from strings.xml in a custom class?Android:如何在自定义类中从 strings.xml 访问字符串数组?
【发布时间】:2013-10-24 20:23:17
【问题描述】:

我想在不扩展自定义类中的 Activity 的情况下获取我的字符串数组。有没有办法做到这一点?

String[] foo_array = getResources().getStringArray(R.array.foo_array); 在不扩展 Activity 的情况下将无法工作,所以我需要一个变通方法。

【问题讨论】:

    标签: android arrays


    【解决方案1】:

    如果你使用 numberpicker 并从 sring xml 传递字符串然后使用这个

    np_Basic_Hight.setMinValue(0);

        np_Basic_Hight.setMaxValue(71);
        np_Basic_Hight.setDisplayedValues(getContext().getResources().getStringArray(R.array.hieght));
    

    【讨论】:

      【解决方案2】:

      将上下文传递给自定义类的构造函数并使用相同

      new CustomClass(ActivityName.this);
      

      然后

      Context mContext;
      public CustomClass(Context context)
      {
          mContext = context;
      }
      

      使用上下文

      String[] foo_array = mContext.getResources().getStringArray(R.array.foo_array);
      

      还要记住

      不要保留对上下文活动的长期引用(对活动的引用应该与活动本身具有相同的生命周期)

      http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html

      也检查一下

      android getResources() from non-Activity class

      编辑:

      改变这个

      public class CustomClass(Context context) 
      {
      }
      

      public class CustomClass
      {
         Context mContext;
         public CustomClass(Context context) // constructor 
         {
          mContext = context;
         }
      }
      

      【讨论】:

      • 当我将我的自定义类更改为 public class CustomClass(Context context) {} 时,它会给我错误提示 Syntax error on token "(", { expected
      • @JosephWebber 你需要有一个构造函数而不改变类声明的语法。检查编辑
      • @JosephWebber 检查它应该工作的编辑并检查这个docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
      • @Raghunandan 谢谢。我误解了你说的话,但我现在记得该怎么做。
      【解决方案3】:

      试试这个,

      Context context=getApplicationContext();
      String[] foo_array = context.getResources().getStringArray(R.array.foo_array);
      

      并且,不要使用 Activity 上下文,因为它与 Activity 生命周期相关联。

      更新

      getApplicationContext() 来自 Context 类。这意味着任何扩展 Context 的东西都有这个方法。这也意味着您将能够从service 或其他资源中使用它。

      但是,如果您自定义的类不扩展 Activity/context,则必须将 Context 作为参数传递才能使用getApplicationContext()

      如果你这样声明你的活动

      myMethod(Activity activity) //this is bad
      

      芽如果像下面这样,

      myMethod(Context context) //this is ok
      

      但是从上面的声明不通过ActivityService Context 因为它们有自己的生命周期。相反,您将使用getApplicationContext()

      【讨论】:

      【解决方案4】:

      您需要将 Activity 上下文传递给自定义类。

      private Context context;
      public CustomClass(Context context)
      {
       this.context=context;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-02-02
        • 2016-12-02
        • 2012-11-24
        • 1970-01-01
        • 2020-10-30
        • 1970-01-01
        • 2021-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多