简体   繁体   English

如何从活动外部访问我的资源?

[英]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.

相关问题 如何从“设置”活动中的“主要活动”访问方法? - How can I access methods from my Main Activity in my Settings activity? 如何从外部项目目录读取资源文件? - How can I read resources file from outside project directory? 如何确定从Java应用程序访问某些第三方程序和资源的方式? - How can I determine the way to access certain third-party programs and resources from my Java app? 如何在运行时从JSF控制器访问位于“ src / main / resources”文件夹中的css文件 - How can I access a css file located in my “src/main/resources” folder from my JSF controller at runtime 如何从AlertDialog的onClickListener中访问Activity的实例变量? - How can I access my Activity's instance variables from within an AlertDialog's onClickListener? 如何从资源构建路径加载ResourceBundle? - How can I load a ResourceBundle from my resources build path? 如何在外部循环中从[0到9]访问字符串列表? - How can I access the Strings list from [0 to 9] outside for loop? 如何从 try catch 块外部访问变量? - How can I access a variable from outside the try catch block? 如何在Activity外访问findViewById() - How access findViewById() outside Activity Android 如何在课堂上访问资源? - Android how can I access resources in class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM