我想创建一个简单的绘图应用程序。我希望能够添加一些线条、圆形和矩形。我想选择任何形状并移动它。我试过这种方式:
- 为每个形状添加一个视图,并在视图的 onDraw 方法中绘制形状
- 将每个视图添加到相对布局
我可以看到所有的形状,但我只能触摸第一个视图,因为它填满了整个屏幕。我在示例中搜索了一个“分层”应用程序的示例,但没有成功
谢谢 :)
编辑:添加代码。
如果我单击矩形,我可以看到日志,但如果我单击圆圈,则没有日志。
编辑 2:哎呀,我忘了在圈子里附上听众...... :( 抱歉
布局 :
public class DrawingView extends RelativeLayout {
public DrawingView(Context context) {
super(context);
this.setBackgroundColor(0xFFFFFFFF);
this.addView(new Circle(context));
this.addView(new Rectangle(context));
}
}
圈子:
public class Circle extends View implements View.OnTouchListener {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Circle(Context context) {
super(context);
this.paint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
this.setMeasuredDimension(100, 100);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(50, 50, 50, this.paint);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("myApp", "cercle");
return false;
}
}
和矩形:
public class Rectangle extends View implements View.OnTouchListener {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Rectangle(Context context) {
super(context);
this.paint.setStyle(Paint.Style.STROKE);
this.setOnTouchListener(this);
this.setX(50);
this.setY(50);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
this.setMeasuredDimension(100, 100);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, 0, 100, 100, this.paint);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("myApp", "Rectangle");
return false;
}
}