开发者

How to access drawable from non activity class

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

But th开发者_运维问答is 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.

Example

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


import com.(package-name).R;

then you can access all your drawable e.g R.drawable.icon.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜