Using of MotionEvent (ACTION_MOVE)

868 Views Asked by At

So I have special question to you: How can I catch buttons when I use move action? How can I handle moves on my screen for buttons(or other elements)?

I used MotionEvent (ACTION_MOVE) but by using that fragment of code i don't get the desired result

in OnCreate

btn1.setOnTouchListener(this); //for all of buttons on Activity

in onTouch

switch(event.getAction()) { 
  case MotionEvent.ACTION_MOVE: 
       //actions
  break;
}

actions will be occur for first button from which the movement starts. In other case nothing will occur

At this time I think that I can use ACTION_MOVE for my Activity not for each button or other elements and save coordinates of buttons(top left and bottom right) to arraylist. And when movement starts I could compare this coordinates and real coordinates of movement. So by that way I could know on which buttons movement was.

Probably I reinvent the wheel. That why I ask for your help)

2

There are 2 best solutions below

8
On BEST ANSWER

Would you explain more clear? From what I see you need probably do two things: First add listener to all buttons and let your activity implement onTouchListener.
Second you need to save initial coordinate for each button in MotionEvent.ACTION_DOWN(if I'm right about syntax).
This way you will have access to all buttons of yours and you can save their coordinates correctly

1
On

You will get the view inside the touch listener, using which you can identify.

Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn3 = (Button) findViewById(R.id.btn3);

btn1.setOnTouchListener(touchListener);
btn2.setOnTouchListener(touchListener);
btn3.setOnTouchListener(touchListener);

private OnTouchListener touchListener = new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            switch (v.getId()) {
            case R.id.btn1:
                //Button 1
                break;

            case R.id.btn2:
                //Button 2
                break;

            case R.id.btn3:
                //Button 3
                break;
            }
        }
        return false;
    }
};