问题描述:

Why do I get the error message The method getResources() is undefined for the type ColorObjectManager?

I use this line to load a Bitmap image:

orange = BitmapFactory.decodeResource(getResources(), R.drawable.pearl_orange);

It's working fine if I'm doing this in another class that I call GameLoop which I make an object of inside the MainActivity class. But it's not working when I trying to do this in the class ColorObjectManager which I make an object of inside the GameLoop class. Do you follow?

Why am I limited to just use this loading part in the GameLoop class and not in the ColorObjectManager class? I thought it would help if I passed the Context to the constructor of ColorObjectManager, but it didn't! I guess I'm missing some knowledge here where I can create objects and not. Can I get some help to sort this out? Thanks!

网友答案:

getResource needs a Context object. If you pass the context to ColorObjectManager you can retrieve resources with context.getResources()

网友答案:

I agree with the answer posted by blackbelt. Pass the activity context to the constructor of ColorObjectManager from your activity class.

     new ColorObjectManger(ActivityName.this); 

Constructor

     Context mContext;
     public ColorObjectManager(Context context)
     {
          this.mContext= context;
     } 

Then use the context to get resources.

Edit:

If you want to use the context only in your load method

     public ColorObjectManager(Context context)
     {
          load(context);
     }  
网友答案:

To get access getResources() , Activity context is required. Your ColorObjectManager is not an Activity. So you need to pass the Activity context to this class.

相关阅读:
Top