使用getResources()在非活动课 [英] Using getResources() in non-activity class

查看:132
本文介绍了使用getResources()在非活动课的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在非活动课使用getResources方法。我如何获得的,参照资源对象,以便我可以访问下的资源文件夹存储在XML文件?

例如:

  XmlPullParser XPP = getResources()的getXML(R.xml.samplexml)。
 

解决方案

您将有一个上下文对象传递给它。无论是如果你有一个引用类的activty,或 getApplicationContext()

 公共类MyActivity延伸活动{
    公共无效的onCreate(包savedInstanceState){
        RegularClass regularClass =新RegularClass(本);
    }
}
 

然后就可以在构造函数中使用它(或者将其设置为一个实例变量):

 公共类RegularClass(){
    私人上下文的背景下;

    公共RegularClass(背景电流){
        this.context =电流;
    }

    公共findResource(){
        。context.getResources()的getXML(R.xml.samplexml);
    }
}
 

凡构造函数接受上下文作为一个参数

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?

Example:

XmlPullParser xpp = getResources().getXml(R.xml.samplexml);

解决方案

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);
    }
}

Where the constructor accepts Context as a parameter

这篇关于使用getResources()在非活动课的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆