在非活动类中使用 getResources() [英] Using getResources() in non-activity class
本文介绍了在非活动类中使用 getResources()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在非活动类中使用 getResources 方法.如何获取对资源"对象的引用,以便我可以访问存储在资源文件夹下的 xml 文件?
I am trying to use getResources method in a non-activity class. How do I get the reference to the "resources" object so that I can access the xml file stored under resources folder?
示例:
XmlPullParser xpp = getResources().getXml(R.xml.samplexml);
推荐答案
您必须将 context
对象传递给它.this
如果您在活动中有对类的引用,或者 getApplicationContext()
You will have to pass a context
object to it. Either this
if you have a reference to the class in an activty, or getApplicationContext()
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}
然后就可以在构造函数中使用(或者设置为实例变量):
Then you can use it in the constructor (or set it to an instance variable):
public class RegularClass(){
private Context context;
public RegularClass(Context current){
this.context = current;
}
public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}
构造函数接受Context
作为参数的地方
Where the constructor accepts Context
as a parameter
这篇关于在非活动类中使用 getResources()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文