自己创建的非Activity类引用getResources()方法问题的解决方法

来源:互联网 发布:淘宝的收货地址怎么看 编辑:程序博客网 时间:2024/06/05 21:03

总结下来,最好的方法,是在继承了Activity的一个activity里面声明一个静态类型的mContext:

private static Context mContext;

然后,在onCreate方法里初始化:

mContext = this;

用get方法获取这个mContext:

public static Context getContext() {
return mContext;
}


以上方法,在我的安卓应用里是可以使用的。


以下 from: http://blog.csdn.net/xyzjl/article/details/9285093   发现有错误, 读者自行甄别吧。


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

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

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

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

有人这么解决:

一、改为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()方法问题的解决方法。

顺便附一片帖子,关于Context的。http://www.360doc.com/content/11/0430/11/4154133_113336620.shtml

0 0
原创粉丝点击