java如何在DragListener中获取画布项以便在其中绘制?
我尝试在画布上绘制一些形状,如果项目被放置到画布上:
public class MainActivity extends AppCompatActivity {
private String selectedItem=null;
private Button circle=null;
private Button rectangle=null;
private Button triangle=null;
private MyTouchListener touch= new MyTouchListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rectangle=(Button)findViewById(R.id.rectangle);
rectangle.setOnTouchListener(touch);
rectangle.setOnDragListener(new MyDragListener());
circle=(Button)findViewById(R.id.circle);
circle.setOnTouchListener(touch);
circle.setOnDragListener(new MyDragListener());
triangle=(Button)findViewById(R.id.triangle);
triangle.setOnTouchListener(touch);
triangle.setOnDragListener(new com.example.dragtest.MainActivity.MyDragListener());
}
private final class MyTouchListener implements View.OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
// selectedButton
final int id = view.getId();
switch(id){
case R.id.circle:
selectedItem="circle";
break;
case R.id.rectangle:
selectedItem="rectangle";
break;
case R.id.triangle:
selectedItem="triangle";
break;
}
return true;
}
return false;
}
}
private final class MyDragListener implements View.OnDragListener {
public boolean onDrag(View v, DragEvent event) {
final int id = v.getId();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
if(id != R.id.dropzone || !(v instanceof Canvas)){
return true;
}
final float x = v.getX();
final float y = v.getY();
final Canvas c = (Canvas)v;
switch(selectedItem){
case "rectangle":
Paint p = new Paint();
p. setARGB(0, 255, 0, 0);
c.drawRect(x,y,x+5,y+5,p);
break;
case "circle":
Paint p = new Paint();
p. setARGB(0, 255, 0, 128);
c.drawCircle(x,y,100,p);
break;
case "triangle":
Paint p = new Paint();
p. setARGB(0, 255, 144, 128);
Point a = new Point(x,y);
Point b = new Point(x-5, y+5);
Point c = new Point(x+5, y+5);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.lineTo(b.x, b.y);
path.lineTo(c.x, c.y);
path.lineTo(a.x, a.y);
path.close();
c.drawPath(path, p);
break;
}
break;
case DragEvent.ACTION_DRAG_ENDED:
default:
break;
}
return true;
}
}
}
但在第86行:
final Canvas c = (Canvas)v;
我得到以下错误:
error: incompatible types: View cannot be converted to Canvas
据我所知,视图获取事件的源代码,如果项目被删除,我希望执行一些代码
因此,我如何检测物品是否掉落:
- 在哪里下车
- 画布中的哪个位置被放下
实际上,我想检查按钮是否落在画布内。你知道我怎么做吗
共 (0) 个答案