错误getResource()在另一个类中

时间:2017-12-21 07:38:35

标签: android android-studio bitmap resources android-resources

此类代码

中的

错误:

 cannot find symbol method getResources()

代码:

public void printPhoto(int img) {

        try {
            Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                    img);
            if(bmp!=null){
                byte[] boleh = Utils.decodeBitmap(bmp);
                mmOutputStream.write(PrinterCommands.ESC_ALIGN_CENTER);
                printText(boleh);
            }else{
                Log.e("Print Photo error", "the file isn't exists");
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("PrintTools", "the file isn't exists");
        }

    }
  

我在另一个类中的所有函数和方法。在我的MainActivity中仅用于按钮和监听器。怎么解决这个问题。我是android studio的初学者。感谢

2 个答案:

答案 0 :(得分:1)

您应该通过Context

代码

public void printPhoto(Context ctx,int img) {

    try {
        Bitmap bmp = BitmapFactory.decodeResource(ctx.getResources(),
                img);

拨打

printPhoto(YourActivityName.this, R.drawable.your_image); // For Activity
printPhoto(getActivity(), R.drawable.your_image); // For Fragment

答案 1 :(得分:0)

Context类中的MainActivity传递给您的自定义类。跟着它 -

public void printPhoto(Context context, int img) {

    try {
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
                img);
        if(bmp!=null){
            byte[] boleh = Utils.decodeBitmap(bmp);
            mmOutputStream.write(PrinterCommands.ESC_ALIGN_CENTER);
            printText(boleh);
        }else{
            Log.e("Print Photo error", "the file isn't exists");
        }

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("PrintTools", "the file isn't exists");
    }

}

并从MainActivity拨打电话。

printPhoto(getApplicationContext(), R.drawable.img);