1

我曾多次在 android 中使用 toast 来显示消息并且从未出现过问题,这包括将它放在方法的内部和外部。但是这次由于某种原因编译器不允许它工作。为什么不允许将 toast 放入下面显示的此方法中?

在这段代码中,我尝试了两种类型的上下文,“ThumbnailsActivity.class”和“this”。

decodeSampleBitmapFromResource 方法位于扩展 Activity 的 Android 类 ThumbnailsActivity.java 中。这里没有什么不寻常的。

  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
4

3 回答 3

3

Chanhe你的方法为:

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

如果要访问非静态上下文,请将所有 toast 放在 return 语句之前,并从方法中删除静态

于 2012-12-10T07:27:14.307 回答
3

您不能直接从方法调用 current ActivityContextstatic

您可以将 current作为参数传递给方法或使您Activity的方法非静态。Contextstatic

于 2012-12-10T07:27:50.837 回答
0

你只需在 getApplicationContext() 上写,然后现在检查,

Toast.makeText(getApplicationContext(),"TEST",Toast.LENGTH_LONG).show();
于 2012-12-10T07:28:37.477 回答