我的应用程序工作正常但是当屏幕方向改变时,表面视图会被清除。我正在使用路径绘制自由的手。我正在尝试使用路径的arraylist将其恢复到原始状态。
下面是我初始化arraylist
的类的构造函数public DrawThread(Context context){
this.context = context;
paths = new ArrayList<Path>(); //this is the arraylist in which i store path.
//path = new Path();
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
}
以下是负责绘制路径的函数
boolean doTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
int X = (int)event.getX();
int Y = (int)event.getY();
switch (eventaction ) {
case MotionEvent.ACTION_DOWN:
path = new Path();
path.moveTo(X, Y);
path.lineTo(X, Y);
break;
case MotionEvent.ACTION_MOVE:
//path.close();
//path.moveTo(lastX, lastY);
path.lineTo(X, Y);
break;
case MotionEvent.ACTION_UP:
path.lineTo(X, Y);
//path.setLastPoint(X, Y);
paths.add(path);
break;
}
drawOnCanvas();
return true;
}
private void drawOnCanvas(){
Canvas canvas = null;
try{
canvas = sHolder.lockCanvas(null);
if(canvas != null & path!= null){
canvas.drawPath(path, paint);
}
}finally {
if(canvas!=null){
sHolder.unlockCanvasAndPost(canvas);
}
}
}
下面是负责将surfaceview恢复到原始状态的函数。
当屏幕方向改变时调用setSurfaceSize。
public void setSurfaceSize(int width , int height){
sWidth = width;
sHeight = height;
redrawall();
}
private void redrawall(){
Canvas canvas = null;
int i = 0;
try{
canvas = sHolder.lockCanvas(null);
if(canvas != null & paths!= null){
if(paths.isEmpty()){
Toast.makeText(context, "empty", Toast.LENGTH_SHORT).show();
}
for (Path pp : paths){
canvas.drawPath(pp, paint);
}
}
}finally {
if(canvas!=null){
sHolder.unlockCanvasAndPost(canvas);
}
}
}
问题是路径(arraylist)始终为空,旋转后屏幕保持空白。
答案 0 :(得分:0)
对于设备的每次旋转,Activity
都会被销毁并重新创建。它会调用onPause()
,onStop()
,并回忆onCreate()
,onStart()
,onResume()
,以便自定义视图。因此,DrawThread
被停止并销毁并重新调用其初始化方法(其构造函数)。然后,每次使用此行创建一个新的ArrayList
:
// this list is obviously empty at its creation ;)
paths = new ArrayList<Path>();
为了防止这种情况,请在轮换之前使用Parcelable
对象存储列表的状态,然后将其恢复。您可能需要创建一个自定义Path
对象来实现Parcelable
对象,然后保存ArrayList
。通过对互联网的一点研究,您可以在视图中找到这些方法:
// Saves current instance of class
@Override
public Parcelable onSaveInstanceState() { ... }
// Restores current instance of class
@Override
public void onRestoreInstanceState(Parcelable state) { ... }
// State of class
private static class SavedState extends BaseSavedState {
...
@Override
public void writeToParcel(Parcel out, int flags) { ... }
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) { ... }
public SavedState[] newArray(int size) { ... }
};
}