Android:如何从自定义类中的strings.xml访问字符串数组?

Jos*_*ber 20 arrays android

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

String[] foo_array = getResources().getStringArray(R.array.foo_array); 没有扩展活动将无法工作,所以我需要一个解决方法.

Rag*_*dan 34

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

new CustomClass(ActivityName.this);
Run Code Online (Sandbox Code Playgroud)

然后

Context mContext;
public CustomClass(Context context)
{
    mContext = context;
}
Run Code Online (Sandbox Code Playgroud)

使用上下文

String[] foo_array = mContext.getResources().getStringArray(R.array.foo_array);
Run Code Online (Sandbox Code Playgroud)

还要记住

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

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

还检查一下

来自非Activity类的android getResources()

编辑:

改变这个

public class CustomClass(Context context) 
{
}
Run Code Online (Sandbox Code Playgroud)

public class CustomClass
{
   Context mContext;
   public CustomClass(Context context) // constructor 
   {
    mContext = context;
   }
}
Run Code Online (Sandbox Code Playgroud)


min*_*haz 6

试试这个,

Context context=getApplicationContext();
String[] foo_array = context.getResources().getStringArray(R.array.foo_array);
Run Code Online (Sandbox Code Playgroud)

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

更新,

getApplicationContext()来自Context类.这意味着扩展Context的任何东西都有这种方法.这也意味着您可以service从其他资源使用此资源.

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

如果你宣布你的活动是这样的

myMethod(Activity activity) //this is bad
Run Code Online (Sandbox Code Playgroud)

如果它像下面的芽,

myMethod(Context context) //this is ok
Run Code Online (Sandbox Code Playgroud)

但从上面的声明不通过ActivityService Context因为他们有自己的生命周期.相反,你会使用getApplicationContext()