错误getResource()在另一个类中

问题描述 投票:1回答:2

此代码不在类mainActivity中

错误:

 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的初学者。谢谢

android android-studio bitmap resources android-resources
2个回答
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

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);
© www.soinside.com 2019 - 2024. All rights reserved.