问题描述
是否可以通过触摸屏幕将所选图形放置在应用程序屏幕上(图形应位于被触摸的位置)?图在可绘制文件夹中。
board.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v,MotionEvent event) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// v.requestPointerCapture();
// }
int touchX = (int) event.getX();
int touchY = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("TAG","touched down: (" + touchX + "," + touchY + ")");
break;
case MotionEvent.ACTION_MOVE:
Log.d("TAG","moving: (" + touchX + "," + touchY + ")");
break;
case MotionEvent.ACTION_UP:
Log.d("TAG","touched up: (" + touchX + "," + touchY + ")");
break;
}
return true;
}
});
解决方法
我有一个解决方案:
RelativeLayout.LayoutParams lp =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);; //Assuming you use a RelativeLayout
ImageView iv=new ImageView(getContext());
lp.setMargins(touchX,touchY,0);
iv.setLayoutParams(lp);
iv.setImageDrawable(getResources().getDrawable(R.drawable.blackstone,null));
((ViewGroup)v).addView(iv);
但是当我触摸屏幕时,应用崩溃了,出现了以下错误:
java.lang.ClassCastException:androidx.appcompat.widget.AppCompatImageView无法转换为android.view.ViewGroup