2012-12-10 38 views
1

我已經在android中用toast來多次顯示消息,從來沒有出現過問題,這包括將它放在方法內部和外部。但是由於某些原因,這次編譯器不允許它工作。爲什麼不允許烤麪包放在下面顯示的方法中?吐司消息編譯錯誤android內部java方法

在這段代碼中,我嘗試了兩種類型的上下文,「ThumbnailsActivity.class」和「this」。

解碼方法decodeSampleBitmapFromResource是Android類ThumbnailsActivity.java中的擴展Activity。這裏沒什麼不尋常的。

public static Bitmap decodeSampledBitmapFromResource(String fileName, int reqWidth, int reqHeight) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(fileName, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeFile(fileName, options); 

     // both of the toasts shown here have compile errors 

    Toast.makeText(ThumbnailsActivity.class, "TEST",Toast.LENGTH_LONG).show(); 

     Toast.makeText(this, "TEST",Toast.LENGTH_LONG).show(); 

}//end decodeSampledBitmapfromresource method 
+0

使用getApplicationContext()而不是此 –

+0

嘗試'ThumbnailsActivity.this' :) –

回答

3

滻你的方法爲:

public Bitmap decodeSampledBitmapFromResource(String fileName, int reqWidth, int reqHeight) { 

     // First decode with inJustDecodeBounds=true to check dimensions 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(fileName, options); 

     // Calculate inSampleSize 
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

     // Decode bitmap with inSampleSize set 
     options.inJustDecodeBounds = false; 

      // both of the toasts shown here have compile errors 

     Toast.makeText(ThumbnailsActivity.this, "TEST",Toast.LENGTH_LONG).show(); 

      Toast.makeText(this, "TEST",Toast.LENGTH_LONG).show(); 

     return BitmapFactory.decodeFile(fileName, options); 



    }//end decodeSampledBitmapfromresource method 

把所有敬酒return語句之前,如果你還想要訪問非靜態上下文從方法刪除靜態

+2

不錯的抓.. :) –

+0

是,這個作品,我並沒有首先注意到這些敬酒是在歸還陳述之後,現在在將它們移到它編譯的回報之上之後。 – Kevik

+0

我不明白爲什麼這個敬酒在返回語句之前編譯好,但在它之後沒有編譯。 – Kevik

3

不能調用當前ActivityContext直接從static方法。

您可以將當前的ActivityContext作爲參數傳遞給static方法或使您的方法爲非靜態方法。

1

你剛剛在getApplicationContext寫(),然後立即檢查,

Toast.makeText(getApplicationContext(),"TEST",Toast.LENGTH_LONG).show();