如何从非活性类访问绘 [英] How to access drawable from non activity class

查看:134
本文介绍了如何从非活性类访问绘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个情况下,我必须使用绘制文件夹我的应用程序的形成非活性类。我试着用父活动具有以下code:

I am in a situation where I have to use the drawable folder of my app form a non activity class. I tried using the parent activity with the following code:

ParentActivity pa = new ParentActivity();
Drawable d = pa.getResources()..getDrawable(R.drawable.icon);`

但是,这将返回我一个 NullPointerException异常
我怎样才能做到这一点?

But this returns me a NulLPointerException. How can I achieve this?

推荐答案

传递上下文对象作为参数传递给非活动类的构造函数。

Pass the context object as a parameter to the constructor of the non Activity class.

然后使用上下文对象来获取资源。

Then use that context object to get the Resources.

示例

public class MyClass {
  Context context;
  public MyClass(Context context) {
      this.context = context;
  }

  public void urMethod() {
    Drawable drawable=context.getResources().getDrawable(R.drawable.icon);
    // use this drawable as u need
  }
}

这篇关于如何从非活性类访问绘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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