博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android 非Activity类引用getResources()方法问题的解决方法
阅读量:6957 次
发布时间:2019-06-27

本文共 1909 字,大约阅读时间需要 6 分钟。

  在进行Android开发的过程中,在一个非Activity类(此处假设类名为MyNewClass)中引用了getResources()方法,如下:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker_red);

结果错误信息提示:MyNewClass.class中没有getResources()方法。

在百度和Google上各种寻找,没有合适的解决办法。

有人这么解决:

可以传递指针给你的activity,在其中你调用getApplicationContext()方法就行了,或者你想用getContext()也可以。

 

一、改为Bitmap bmp = BitmapFactory.decodeResource(Context.getResources(), R.drawable.marker_red);和Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.marker_red);都不行。

 

如果你试了,就知道不行(反正我的不行,但是如果在Activity类中应该是可以的)。

 

二、在Acitivity里面作如下改动:

 

public static Resources resourcesInstance;
resourcesInstance=this.getResources();

 

MyNewClass.class这么引用:

 

Bitmap bitmap = BitmapFactory.decodeResource(MyActivity.resourcesInstance, R.drawable.test);

这样来,代码没有错,但是是出现了NullPointerException的程序运行崩溃的情况。

 

虽然问题没有解决,但是看到这样两句话:

 

在类的构造函数中传一个Context(如Activity或者Application,Service)进来”和“android.content.Context,getResources建立在Activity基础之上”。

 

受此启发,找到两种解决办法:

 

方法一:在MyNewClass.class中创建getResources()方法:

 

private Resources getResources() {

// TODO Auto-generated method stub
Resources mResources = null;
mResources = getResources();
return mResources;
}

 

你会发现错误没有了,而且运行结果正常。

 

方法二:在MyActivity.class的构造函数中进行Context传递。声明一个Context,并且构造方法getContext()。具体代码如下:

 

在MyActivity.class中进行Context传递:

 

public class MyActivity extends Activity {

       ……

 

       ……

private static Context Context = null;
……

 

       ……

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

 

                setContentView(R.layout.view);

 

        ……

 

       ……

 

      public static Context getContext() {

return Context;
}

 

在MyNewClass.class进行方法的引用:

 

Bitmap bmp = BitmapFactory.decodeResource(MyActivity.getContext().getResources(), R.drawable.marker_red);

 

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

以上,就是针对自己创建的非Activity类引用getResources()方法问题的解决方法。

 

 

转载地址:http://kimil.baihongyu.com/

你可能感兴趣的文章
halcon算子翻译——copy_image
查看>>
使用Haar分类器进行面部检测
查看>>
Makefile-2
查看>>
获取页面中出现次数最多的三个标签以及出现次数
查看>>
访问WEB-INF目录中的文件
查看>>
web接口开发与测试
查看>>
php -- php控制linux关机、重启、注销
查看>>
十.python面向对象(itme)
查看>>
Python下selenium的简单用法
查看>>
multiset的应用
查看>>
我的mysql的学习记录
查看>>
Codeforces Round #416 (Div. 2)(A,思维题,暴力,B,思维题,暴力)
查看>>
NYOJ 题目77 开灯问题(简单模拟)
查看>>
模式识别
查看>>
设置文本编辑器的按回车时触发的事件
查看>>
关于android手机不能打印Log日志
查看>>
hdu 2157 How many ways?? **
查看>>
xcode8 更新cocoapods
查看>>
习题:海盗船(广搜)
查看>>
auto_ptr
查看>>