[英]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: 使用以下代码在
ImageDownloader
类中创建一个新的构造函数 :
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. 您需要将Context对象传递给ImageDownloader类或方法。 You can then call getResources() on the Context object.
然后,您可以在Context对象上调用getResources()。 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.
鉴于Activity和Service都扩展了Context,即使您无权访问Activity,也可以在Service中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.