Android Drag and drop of button

前端 未结 3 604
旧时难觅i
旧时难觅i 2021-01-05 22:28

I am working in android, I am using a button. Now I want to perform drag and drop of this button.

This is my main.xml

 

        
相关标签:
3条回答
  • 2021-01-05 22:46

    I resolved my problem like this.

        @Override
         public boolean onTouch(View view, MotionEvent me) {
        if (me.getAction() == MotionEvent.ACTION_DOWN) {
            status = START_DRAGGING;
    
    
        }
        if (me.getAction() == MotionEvent.ACTION_UP) {
            status = STOP_DRAGGING;
            Log.i("Drag", "Stopped Dragging");
        } else if (me.getAction() == MotionEvent.ACTION_MOVE) {
            if (status == START_DRAGGING) {
                System.out.println("Dragging");
    
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        50, 50);
                layoutParams.setMargins((int) me.getRawX() - 25,
                        (int) me.getRawY() - 50, 0, 0);
                layout.removeView(btn);
                layout.addView(btn, layoutParams);
    
                btn.invalidate();
            }
        }
        return false;
    }
    

    Now its working fine.

    0 讨论(0)
  • 2021-01-05 22:54

    you should get button's layout params, set left, right, top, bottom and set these layout params back to button

    0 讨论(0)
  • 2021-01-05 23:11

    Try returning true from onTouch() method. That might work out. In one of my app it worked as return false was not moving the view as per my touch movement but return true statement solved it.

    0 讨论(0)
提交回复
热议问题