import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
public class DrawingActivity extends Activity {
private ArrayList _graphics = new ArrayList();
private Paint mPaint;
Handler myHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
myview.invalidate();
};
};
Myview myview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(new DrawingPanel(this));
mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(0xFFFFFF00);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
myview = new Myview(this);
myview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
setContentView(myview);
myHandler = new Handler();
}
class Myview extends View {
public Myview(Context context) {
super(context);
}
Path path;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
path = new Path();
path.moveTo(event.getX(), event.getY());
path.lineTo(event.getX(), event.getY());
_graphics.add(path);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
path.lineTo(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_UP) {
path.lineTo(event.getX(), event.getY());
}
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
for (Path path :_graphics) {
// canvas.drawPoint(graphic.x, graphic.y, mPaint);
canvas.drawPath(path, mPaint);
}
}
}
}
这里编译器显示该行中的错误类型不匹配:无法从元素类型Object转换为Path ---------- for(Path path:_graphics){此处出现问题
答案 0 :(得分:0)
您的ArrayList是无类型的,因此即使您可能只将那些类型的对象放在那里,编译器也不会知道它。您需要使用泛型(如果Android上的Java支持它),例如
ArrayList<Path> _graphics = new ArrayList<Path>();
或重写循环,以便您可以在从列表中获取元素时强制转换元素。
for (int c=0; c< _graphic.size(); ++c ) {
Path p = (Path)_graphics.get(c);
....
}
祝你好运。