首页 > 解决方案 > 通过触摸将图形放在屏幕上

问题描述

是否可以通过触摸屏幕将所选图形放在应用程序屏幕上(图形应该在触摸的地方)?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;
            }
        });

标签: javaandroidimageview

解决方案


我有一个解决方案是:

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


推荐阅读