开发者

Accessing Drawable resources from a non context class

开发者 https://www.devze.com 2023-01-23 17:20 出处:网络
I\'m defining a class that sets a Drawable attribute in an object. The problem is that I can\'t access the getResource().getDrawable(int resourceId) method unless I have some Context.

I'm defining a class that sets a Drawable attribute in an object. The problem is that I can't access the getResource().getDrawable(int resourceId) method unless I have some Context. What I did was to send to that class an activity instance (let's call it "act") and then I did:

act.getResources().getDrawable(R.drawable.whellchair)

but, when executing that line it开发者_运维知识库 throws a NullPointerException.

When idea how to accomplish this?


I found the problem! I'm using a singleton and I put the line accessing the "act" in a static method... how fool of me ...

Sorry and thank you Juhani for the comment :)


Pass that the application context to the constructor of your class. In the main application class you just get the context by invoking the getApplication() method if you need the a lifetime aware context or getApplicationContext() if you need a the context which is tied to the current process.

Example:

private Context ctx = getApplication();

... some code ...

MyClass myClass = new MyClass(ctx);

Your classes' constructor of course has to handle the context accordingly (i.e. setting a private member of type Context to the passed value) like this.

private Context ctx = null;

public MyClass(ctx) {
    this.ctx = ctx;
}

Then you can use the context for whatever you need.

0

精彩评论

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