问题描述
我想在不扩展自定义类中的Activity的情况下获取字符串数组。有没有办法做到这一点?
I'd like to get my string-array without extending Activity in my custom class. Is there a way to do this?
String [] foo_array = getResources()。getStringArray(R.array.foo_array);
没有扩展Activity,所以我需要解决方法。
String[] foo_array = getResources().getStringArray(R.array.foo_array);
will not work without extending Activity, so I need a work-around.
推荐答案
将上下文传递给自定义类的构造函数,并使用相同的
Pass the context to the constructor of custom class and use the same
new CustomClass(ActivityName.this);
然后
Context mContext;
public CustomClass(Context context)
{
mContext = context;
}
使用上下文
String[] foo_array = mContext.getResources().getStringArray(R.array.foo_array);
也请记住
不要保留对上下文活动的长期引用(对活动的引用应与活动本身具有相同的生命周期)
Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
也请检查此
编辑:
更改此
public class CustomClass(Context context)
{
}
到
public class CustomClass
{
Context mContext;
public CustomClass(Context context) // constructor
{
mContext = context;
}
}
这篇关于Android:如何在自定义类中从strings.xml访问字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!