2012-08-16 50 views
0

我有两个类,A类叫做应用和B类称为选项 我想A级摆脱B级的资源,但我发现了错误来自不同类的Android getResources

我的错误得到

Cannot make a static reference to the non-static method getResources() from the type ContextWrapper 

上A类

public static void applyBitmap(int resourceID) { 
    BitmapFactory.Options opt = new BitmapFactory.Options(); 
    opt.inScaled = true; 
    opt.inPurgeable = true; 
    opt.inInputShareable = true; 
    Bitmap brightBitmap = BitmapFactory.decodeResource(getResources(), resourceID, opt); 
    brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 100, 100, false); 
    MyBitmap = brightBitmap; 

} 

和示例的资源按钮的功能在B类

// the 34th button 
    Button tf = (Button) findViewById(R.id.tFour); 
    tf.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      Apply.applyBitmap(R.drawable.tFour); 

     } 
    }); 

note *:之前当功能在B类中的功能很好,但知道我认为我需要静态资源,但是如何?我不知道

我试图Option.getResources()但没有奏效,它给出了一个错误

+0

如果你删除从A类的 “静态”?你需要静态吗?其实它对java的基本理解。我虚心地建议你重新阅读Java基础知识。 – 2012-08-16 02:21:16

+1

Yoi声明:public static void applyBitmap(int resourceID) – 2012-08-16 02:25:35

回答

1

您正在访问getResources()没有一个Context参考。由于这是一种静态方法,因此您只能访问该类中的其他静态方法而不提供参考。

相反,你必须通过Context作为参数:

// the 34th button 
Button tf = (Button) findViewById(R.id.tFour); 
tf.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) { 
     Apply.applyBitmap(v.getContext(), R.drawable.tFour); // Pass your context to the static method 
    } 
}); 

然后,你必须引用它getResources()

public static void applyBitmap(Context context, int resourceID) { 
    BitmapFactory.Options opt = new BitmapFactory.Options(); 
    opt.inScaled = true; 
    opt.inPurgeable = true; 
    opt.inInputShareable = true; 
    Bitmap brightBitmap = BitmapFactory.decodeResource(context.getResources(), resourceID, opt); // Use the passed context to access resources 
    brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 100, 100, false); 
    MyBitmap = brightBitmap; 
} 
+0

它工作完美,谢谢=) – 2012-08-16 02:37:56

相关问题