我正在制作一个绘图应用,当我按下时,应用程序会随机崩溃。我无法弄清楚如何解决它,并且不知道从哪里开始。我不知道它是List还是时间,还是别的什么。这是我的代码:
package com.orangewhales.paint.views;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
public class PaintView extends SurfaceView implements Callback {
boolean run = true;
Thread tUpdate;
public List<PaintPath> paths = new ArrayList<PaintPath>();
public Paint stroke = new Paint();
@Override
public void draw(Canvas canvas) {
// TODO Auto-generated method stub
super.draw(canvas);
canvas.drawRGB(255, 255, 255);
for (PaintPath path : paths) {
canvas.drawPath(path.path, path.paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
Path current = new Path();
current.moveTo(event.getX(), event.getY());
paths.add(new PaintPath(current, stroke));
break;
case MotionEvent.ACTION_MOVE:
PaintPath path = paths.get(paths.size() - 1);
path.path.lineTo(event.getX(), event.getY());
break;
}
return true;
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
stroke.setStyle(Style.STROKE);
stroke.setColor(Color.BLACK);
stroke.setStrokeWidth(10);
tUpdate = new Thread() {
public void run() {
while (run) {
Canvas c = getHolder().lockCanvas();
draw(c);
getHolder().unlockCanvasAndPost(c);
update();
try {
sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
getHolder().addCallback(this);
}
public void update() {
// TODO Auto-generated method stub
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
tUpdate.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
run = false;
try {
tUpdate.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
我有一段时间没有触及我的Android SDK。所以我将从一个问题开始。
你说当按下GUI时,应用程序会随机崩溃。在函数onTouchEvent中,首先发生哪个动作,ACTION_DOWN还是ACTION_MOVE? 我希望它定义明确,但我们不能假设。
我发现函数“PaintPath path = paths.get(paths.size() - 1)”中的代码是可疑的,因为无论如何,paths.size都可以为0。
我认为密切监视onTouchEvent函数是个好主意,可以使用调试器。如果您没有其他内容,请记录消息。
修复随机间歇性问题是工作的一部分。从中学习并享受乐趣。