How to access drawable from non activity class

房东的猫 提交于 2019-12-06 23:58:07

问题


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 this returns me a NulLPointerException. How can I achieve this?


回答1:


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



回答2:


import com.(package-name).R;

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



来源:https://stackoverflow.com/questions/6214386/how-to-access-drawable-from-non-activity-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!