此代码不在类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的初学者。谢谢
你应该通过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
将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);