Android: Shall I have access to resources from my own class?
I my project I have a class that in this class I want to have access to properties of a picture. But I don't want to show it through this class. In this class I just want to know width and height of image and do some mathematical functions to return something.
My problem is I can't have access to resources. for example, when I write
image = BitmapFactory.decodeResource(this.getResources(), R.drawable.tasnim);
It says the method getResources() in undefined for the type Stego (stego is my class name).
Please tell me what should I do?
public class Stego()
{
Public Stego(){
开发者_如何学编程 image = BitmapFactory.decodeResource(this.getResources(), R.drawable.tasnim);
imWidth = image.getWidth();
imHeight = image.getHeight();
}
}
The getResources()
function belongs to the Context
class. So unless your Stego
class directly (or indirectly) extends Context
, there is no getResources()
function available.
So what you need to do is pass along a reference to your application's context (e.g. in the constructor of your Stego
class or similar). Or if all you need is a single resource ID it might be easier to just pass along that ID.
This could for instance look like this:
public class Stego()
{
Public Stego(Context myAppContext){
image = BitmapFactory.decodeResource(myAppContext.getResources(), R.drawable.tasnim);
imWidth = image.getWidth();
imHeight = image.getHeight();
}
}
From your activity you can then initialize an instance of your Stego
class like this:
Stego stego = new Stego(this);
精彩评论