android: move a view on touch move (ACTION_MOVE)

后端 未结 11 2212
终归单人心
终归单人心 2020-11-22 13:54

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

11条回答
  •  悲哀的现实
    2020-11-22 14:16

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

提交回复
热议问题