Android 安卓为什么在绘制位图时会出现OutOfMemory错误?
我有一个带有tabHost的fragmentActivity。每个选项卡内部都有一个片段,在屏幕上显示一些按钮。 以下代码是按钮表:Android 安卓为什么在绘制位图时会出现OutOfMemory错误?,android,bitmap,out-of-memory,ondraw,Android,Bitmap,Out Of Memory,Ondraw,我有一个带有tabHost的fragmentActivity。每个选项卡内部都有一个片段,在屏幕上显示一些按钮。 以下代码是按钮表: public class ButtonTable extends Button { private Paint paint= new Paint(); private Bitmap bmp= null; private Table table= null; int width= 0; int height= 0;
public class ButtonTable extends Button {
private Paint paint= new Paint();
private Bitmap bmp= null;
private Table table= null;
int width= 0;
int height= 0;
boolean adjustmentForm= false;
private WeakReference<Bitmap> resizedBitmap;
public ButtonTable(Context context, Table table, int width, int height) {
super(context);
this.table=table;
this.width= width;
this.height= height;
setWidth(width);
setHeight(height);
setBitmapImage();
setBackgroundColor(INVISIBLE);
}
[...]
public void setBitmapImage(){
int resurce= R.drawable.rectangle6;
if(table.getTableType().equals("Circle6")){
resurce=R.drawable.circle6;
adjustmentForm= true;
}
if(table.getTableType().equals("Circle4")){
resurce= R.drawable.circle4;
adjustmentForm= true;
}
[...]
bmp = BitmapFactory.decodeResource(getResources(), resurce);
if(adjustmentForm){
bmp = Bitmap.createScaledBitmap(bmp, height, height, true);
}else{
bmp = Bitmap.createScaledBitmap(bmp,width, height, true);
}
resizedBitmap = new WeakReference<Bitmap>(bmp);
}
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
if(adjustmentForm){
canvas.drawBitmap(resizedBitmap.get(), ((width-height)/2), 0, null);
}else{
canvas.drawBitmap(resizedBitmap.get(), 0, 0, null);
}
}
}
公共类按钮可扩展按钮{
私人油漆=新油漆();
私有位图bmp=null;
私有表=空;
整数宽度=0;
整数高度=0;
布尔adjustmentForm=false;
私有WeakReference resizedBitmap;
公共按钮表(上下文、表格、整数宽度、整数高度){
超级(上下文);
这个表=表;
这个。宽度=宽度;
这个。高度=高度;
设置宽度(宽度);
设置高度(高度);
setBitmapImage();
setBackgroundColor(不可见);
}
[...]
公共无效setBitmapImage(){
int resurce=R.可拉伸矩形6;
if(table.getTableType().equals(“Circle6”)){
resurce=R.drawable.circle6;
adjustmentForm=true;
}
if(table.getTableType().equals(“Circle4”)){
resurce=R.可绘制圆圈4;
adjustmentForm=true;
}
[...]
bmp=BitmapFactory.decodeResource(getResources(),resurce);
如果(调整表){
bmp=Bitmap.createScaledBitmap(bmp,高度,高度,真);
}否则{
bmp=Bitmap.createScaledBitmap(bmp,宽度,高度,真);
}
resizedBitmap=新的WeakReference(bmp);
}
@凌驾
公共空白onDraw(画布){
super.onDraw(帆布);
如果(调整表){
drawBitmap(resizedBitmap.get(),((宽-高)/2),0,null);
}否则{
drawBitmap(resizedBitmap.get(),0,0,null);
}
}
}
如果我在选项卡之间移动一段时间,在大约10/15个选项卡更改之后,应用程序会因为OutOfMemoryError而停止。为什么?我解决了我的问题。
我在片段中实现了onDestroyView()。更改选项卡时,片段不会调用onDestroy()(不会完成其生命周期),但会调用onDestroyView(),然后使用onCreateView()重新启动。片段从后堆栈返回布局。
您的应用程序超出了为堆中的应用程序分配的内存,您将出现内存不足异常。你需要缩小图像。嗯,在这种情况下不是。。。因为他没有在位图上调用recycle()。。。另外,使用WeakReference在这里并没有意义,因为他在这里使用的是“非弱引用”工具书:上面两条注释的组合
@Override
public void onDestroyView() {
super.onDestroyView();
layoutHall.removeAllViewsInLayout();
}