如何从没有上下文的类中调用 getResources()? [英] How to call getResources() from a class which has no context?

查看:31
本文介绍了如何从没有上下文的类中调用 getResources()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的申请中,我有很多课程和活动.Droid 是一个没有上下文的类.Mygame 是一个扩展 SurfaceView 并实现 SurfaceHolder.Callback 的类.我正在 mygame 类中创建一个 Droid 对象并为其设置背景图像和位置.下面给出了我为此编写的代码.

In my application I have many classes and activities. Droid is a class which does not have context. Mygame is a class which extends SurfaceView and implements SurfaceHolder.Callback. I am creating an object of Droid in mygame class and setting the background image and position for it. The code I have written for this is given below.

block1 = new Droid(BitmapFactory.decodeResource(getResources(), R.drawable.birdpic), 100, 10);

Droid 类的构造函数如下.

The constructor of Droid class is given below.

public Droid(Bitmap bitmap, int x, int y) {

    this.bitmap = bitmap;
    this.x = x;
    this.y = y;
}   

在特定情况下,我必须从 Droid 类本身设置 Droid 对象的背景图像和位置.这里我面临这个问题.下面是执行此操作的代码片段.

In a particular scenario i have to set the background image and position of the Droid object from the Droid class itself.Here i am facing the issue.Given below is the code snippet to do this.

if(checkflag)
{
    myObj.centerblock=new Droid(BitmapFactory.decodeResource(getResources(), R.drawable.blast), myObj.xpos, myObj.ypos);
}   

问题在于 Droid 类没有上下文.所以我不能在这里使用 getResources().我已经尝试了下面的代码,但它崩溃了.

The problem is that the Droid class has no context. So I cannot use getResources() here. I have tried the code below but it crashes.

if(checkflag)
{
    myObj.centerblock=new Droid(BitmapFactory.decodeResource(myObj.getResources(), R.drawable.blast), myObj.xpos, myObj.ypos);
}

谁能帮帮我.我只想设置背景图像并将其定位到 Droid 类本身的 Droid 对象.

Can anybody help me. I just want to set the background image and position it for the Droid object from the Droid class itself.

推荐答案

上下文是系统的句柄;它提供诸如解析资源、获取对数据库和首选项的访问等服务.它是一个接口",允许访问特定于应用程序的资源和类以及有关应用程序环境的信息.您的活动和服务还扩展了 Context 以继承所有这些方法来访问应用程序运行所在的环境信息.

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

这意味着如果要获取/修改有关资源的某些特定信息,则必须将上下文传递给特定类.您可以在构造函数中传递上下文,如

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

这篇关于如何从没有上下文的类中调用 getResources()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆