此类代码
中的错误:
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的初学者。感谢
答案 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);