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

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

问题描述

在我的应用我有很多课程和活动。机器人是不具有上下文一个类。 Mygame是延伸SurfaceView并实现SurfaceHolder.Callback一类。 我创建的Droid的mygame类的对象,并设置背景图片和位置吧。在code我已经为这个写在下面给出。

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;
}   

在特定的情况下,我必须设置背景图片,并从itself.Here我面临着以下issue.Given Droid的类对Droid对象的位置是code片段来做到这一点。

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()在这里。我曾尝试下面的code,但它崩溃。

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.

推荐答案

一个上下文是一个处理系统;它提供的服务,如解决资源,从而获得对数据库的访问和preferences,等等。它是一个接口,允许访问应用特定资源和有关应用程序的环境的类和信息。你的活动和服务也扩大背景下,以它们继承了所有的方法来访问该应用程序运行环境的信息。

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天全站免登陆