简体   繁体   中英

How can I access my resources from outside of an Activity?

I have the following code:

Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
imageView.setImageBitmap(bMap);

I am getting the error:

The method getResources() is undefined for the type ImageDownloader

How can I access my resources?

Create a new Constructor in your ImageDownloader class with following code:

public ImageDownloader(Activity mActivity){

// create a class level activity object in your ImageDownloader class.
   activity = mActivity;
}

Now you just need to change your download code a bit:

Bitmap bMap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.icon);
imageView.setImageBitmap(bMap);

Hope this helps!!

You need to pass a Context object to either your ImageDownloader class or the method. You can then call getResources() on the Context object. Given that both Activity and Service extend Context, you can use this from within a Service even when you don't have access to an Activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM