Permalink
Browse files

设备旋转后,通过Parcelable接口保存绘制的自定义矩形框。

  • Loading branch information...
li2 committed Nov 11, 2015
1 parent d581baa commit 2d58e5e4ede7c0ff25b29e90db8dbdad3974dd7d
@@ -5,5 +5,6 @@
如果找不到,应用将崩溃。 -->
<me.li2.android.boxdrawingview.BoxDrawingView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/boxDrawingView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
@@ -6,12 +6,15 @@
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class BoxDrawingView extends android.view.View {
public class BoxDrawingView extends View {
public static final String TAG = "BoxDrawingView";
private Box mCurrentBox;
@@ -101,4 +104,64 @@ public boolean onTouchEvent(MotionEvent event) {
return true;
}
// prevent custom views from losing state across screen orientation changes
// http://stackoverflow.com/a/3542895/2722270
static class BoxDrawingState extends BaseSavedState {
Box currentBox;
ArrayList<Box> boxes;
BoxDrawingState(Parcelable superState) {
super(superState);
}
private BoxDrawingState(Parcel in) {
super(in);
currentBox = (Box)in.readValue(null);
in.readList(boxes, null);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeValue(currentBox);
out.writeList(boxes);
}
@Override
public String toString() {
return "BoxDrawingView.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " Boxes=" + boxes + "}";
}
Parcelable.Creator<BoxDrawingState> CREATOR = new Parcelable.Creator<BoxDrawingState>() {
@Override
public BoxDrawingState createFromParcel(Parcel in) {
return new BoxDrawingState(in);
}
@Override
public BoxDrawingState[] newArray(int size) {
return new BoxDrawingState[size];
}
};
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
BoxDrawingState boxDrawingState = new BoxDrawingState(superState);
boxDrawingState.currentBox = mCurrentBox;
boxDrawingState.boxes = mBoxes;
return boxDrawingState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
BoxDrawingState boxDrawingState = (BoxDrawingState) state;
super.onRestoreInstanceState(boxDrawingState.getSuperState());
mCurrentBox = boxDrawingState.currentBox;
mBoxes = boxDrawingState.boxes;
}
}
@@ -5,6 +5,5 @@
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry exported="true" kind="lib" path="libs/android-support-v4.jar"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>

0 comments on commit 2d58e5e

Please sign in to comment.