自定义View的布局文件:
<com.wanj.draganddrawactivity.BoxDrawingView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/BoxDrawingView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
如果要使用View的onSaveInstanceState()、onRestoreInstanceState(Parcelable state)这2个方法,那么自定义的view必须指定id。
自定义View的代码:
public class BoxDrawingView extends View {
private static final String TAG = "BoxDrawingView";
private Box mCurrentBox;
private List<Box> mBoxen = new ArrayList<>();
private Paint mBoxPaint;
private Paint mBackgroundPaint;
public BoxDrawingView(Context context) {
this(context, null);
}
// 这里之所以添加了两个构造方法,是因为视图可从代码或者布局文件实例化。从布局文件中
// 实例化的视图可收到一个AttributeSet实例,该实例包含了XML布局文件中指定的XML属性。
// 即使不打算使用构造方法,按习惯做法也应添加它们。
public BoxDrawingView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mBoxPaint = new Paint();
mBoxPaint.setColor(0x22ff0000);
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(0xfff8efe0);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPaint(mBackgroundPaint);//画背景图
for (Box box : mBoxen) {
float left = Math.min(box.getOrigin().x, box.getCurrent().x);
float right = Math.max(box.getOrigin().x, box.getCurrent().x);
float top = Math.min(box.getOrigin().y, box.getCurrent().y);
float bottom = Math.max(box.getOrigin().y, box.getCurrent().y);
canvas.drawRect(left, top, right, bottom, mBoxPaint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
PointF current = new PointF(event.getX(), event.getY());
String action = "";
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
action = "ACTION_DOWN";
mCurrentBox = new Box(current);
mBoxen.add(mCurrentBox);
break;
case MotionEvent.ACTION_MOVE:
action = "ACTION_MOVE";
if (mCurrentBox != null) {
mCurrentBox.setCurrent(current);
invalidate(); //该方法强制本视图重新绘制自己,这样在屏幕拖拽时就能够实时看到矩形框
}
break;
case MotionEvent.ACTION_UP:
action = "ACTION_UP";
mCurrentBox = null;
break;
case MotionEvent.ACTION_CANCEL:
action = "ACTION_CANCEL";
mCurrentBox = null;
break;
}
Log.i(TAG, action + " at x = " + current.x + " , y = " + current.y);
return true;
}
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
Parcelable parcelable = super.onSaveInstanceState();
bundle.putParcelable("super_data", parcelable);
bundle.putSerializable("save_data", (Serializable) mBoxen);
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle) state;
Parcelable superData = bundle.getParcelable("super_data");
mBoxen = (List<Box>) bundle.getSerializable("save_data");
super.onRestoreInstanceState(superData);
}
}
进行状态保存的时候,需要通过Bundle传递数据(View默认使用Parcelable传递数据,很不方便)。
通过在onSaveInstanceState()方法中,用Bundle对象保存父视图的状态,并且保存现有的Box线性表的实例mBoxen。
在onRestoreInstanceState(Parcelable state)中取出已保存的父视图的状态并把状态传递给超类,同时把已保存的实例的值赋值给mBoxen,达到屏幕旋转后View视图的内容不改变的目的。