【问题标题】:How can I access my resources from outside of an Activity?如何从 Activity 外部访问我的资源?
【发布时间】:2011-05-18 10:51:51
【问题描述】:
我有以下代码:
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
imageView.setImageBitmap(bMap);
我收到错误:
The method getResources() is undefined for the type ImageDownloader
如何访问我的资源?
【问题讨论】:
标签:
java
android
resources
bitmap
imageview
【解决方案1】:
使用以下代码在您的 ImageDownloader 类中创建一个新的 构造函数:
public ImageDownloader(Activity mActivity){
// create a class level activity object in your ImageDownloader class.
activity = mActivity;
}
现在您只需要稍微更改一下您的下载代码:
Bitmap bMap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.icon);
imageView.setImageBitmap(bMap);
希望这会有所帮助!
【解决方案2】:
您需要将Context 对象传递给您的 ImageDownloader 类或方法。然后,您可以在 Context 对象上调用 getResources()。鉴于 Activity 和 Service 都扩展了 Context,即使您无权访问 Activity,您也可以在 Service 中使用它。