2012-08-16 22 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