Search code examples
androidandroid-studioontouchlistener

How can I move an object around the screen by dragging in Android?


So in my layout I have this ball which I want to drag around the screen. I tried using the onTouch() method, and these are my results:
1)((Button)findViewById(R.id.ball)).setY(event.getY());
((Button)findViewById(R.id.ball)).setX(event.getX());
This one is very glitchy for some reason. I try to move the ball and it just quickly goes back and forth between two different places.
2) ((Button)findViewById(R.id.ball)).setY(event.getRawY());
((Button)findViewById(R.id.ball)).setX(event.getRawX());
This one works a bit smoother, but when I start the movement the ball just teleports to some other place. It works fine except for that part where it "teleports"

What I want to achieve:
A normal drag movement of the ball where the ball is right beneath the finger (x and y coordinates of the ball match the x and y coordinates of the touch)

I can add screen recordings explaining the two cases above if needed


Solution

  • First make your activity implement View.OnTouchListener and import the requested method:

    public class MyActivity extends AppCompatActivity implements View.OnTouchListener {}
    

    Then change newly created onTouch method like below:

    float dX, dY;
    
    @Override
    public boolean onTouch(View view, MotionEvent event) {
    
    switch (event.getAction()) {
    
        case MotionEvent.ACTION_DOWN:
    
            dX = view.getX() - event.getRawX();
            dY = view.getY() - event.getRawY();
            break;
    
        case MotionEvent.ACTION_MOVE:
    
            view.animate()
                    .x(event.getRawX() + dX)
                    .y(event.getRawY() + dY)
                    .setDuration(0)
                    .start();
            break;
        default:
            return false;
    }
    return true;
    }
    

    and finally set this onTouch method to your view:

    ball.setOnTouchListener(this);