java - 通过触摸将图形放在屏幕上
问题描述
是否可以通过触摸屏幕将所选图形放在应用程序屏幕上(图形应该在触摸的地方)?Img 在可绘制文件夹中。
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,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
推荐阅读
- data-analysis - Orange中的时间序列预测
- reactjs - 如何展开被点击的卡片并且不会触发其他卡片展开?
- javascript - 打字稿扩展历史对象自定义状态属性
- java - 使用 RSAPrivateKey(而不是 RSAPrivateCrtKey)将 RSA 私钥保存到 Android KeyStore
- java - Java CompletionService 如何管理多个任务提交?
- android - 如何不时从 Firebase 实时数据库接收数据
- python - 如何在 cifar-10 中选择特定的类
- powershell - 有没有办法用按钮在 Powershell 中发送电子邮件?
- javascript - 错误,同时将元素从 mongodb 推送到数组
- android - 如何使用 Android studio 编译一个 apex(Android Pony EXpress)?