android: move a view on touch move (ACTION_MOVE)

Zelter Ady picture Zelter Ady · Feb 22, 2012 · Viewed 202.5k times · Source

I'd like to do a simple control: a container with a view inside. If I touch the container and I move the finger, I want to move the view to follow my finger.

What kind of container (layout) should I use? How to do this?

I don't need to use a surface, but a simple layout.

Answer

Andrew picture Andrew · Jun 28, 2015

I've found an easy approach to do that with the ViewPropertyAnimator:

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;
}