该应用程序应该保存它在方向更改时绘制的视图,但它没有。谁能说出问题出在哪里?
我没有收到任何错误,但是当我更改设备方向时,视图会重新启动,而不会保存我绘制的内容。
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
conAdd();
}
public DrawingView(Context context) {
super(context);
conAdd();
}
private void conAdd() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.GREEN);
paint.setStyle(Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(width);
path = new Path();
setOnTouchListener(this);
setBackgroundColor(Color.BLACK);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
Canvas canvasNew = new Canvas();
canvasNew.setBitmap(bitmap);
canvas = canvasNew;
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, paint);
canvas.drawBitmap(bitmap, 0, 0, paint);
}
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
path.reset();
path.moveTo(x, y);
invalidate();
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (Math.abs(x - lastX) > 4 || Math.abs(y - lastY) > 4) {
path.quadTo(lastX, lastY, (lastX + x) / 2, (lastY + y) / 2);
invalidate();
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
path.lineTo(x, y);
canvas.drawPath(path, paint);
}
lastX = x;
lastY = y;
return true;
}
@Override
protected Parcelable onSaveInstanceState() {
Bundle inBox = new Bundle();
inBox.putParcelable("draw", super.onSaveInstanceState());
inBox.putParcelable("bitmap", bitmap);
return super.onSaveInstanceState();
}
@Override
protected void onRestoreInstanceState(Parcelable state)
{
if (state instanceof Bundle) {
Bundle outBox = (Bundle) state;
this.bitmap = outBox.getParcelable("bitmap");
super.onRestoreInstanceState(outBox.getParcelable("draw"));
return;
}
super.onRestoreInstanceState(state);
}
}