android java方法里面的toast message编译错误

时间:2012-12-10 07:25:24

标签: android compiler-errors toast

我已经在android中使用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

3 个答案:

答案 0 :(得分: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语句之前放入所有toast,如果要访问非静态上下文,还要从方法中删除static

答案 1 :(得分:3)

您无法直接通过Activity方法调用当前Context的{​​{1}}。

您可以将当前static的{​​{1}}作为参数传递给Activity方法,或者将您的方法设为非静态。

答案 2 :(得分:0)

你只需在getApplicationContext()上写一下,然后立即检查,

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