android: move a view on touch move (ACTION_MOVE)

后端 未结 11 2349
终归单人心
终归单人心 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:22

    Following the @Andrey approach, if you want to move the view from its center, you only have to substract the view's half height and width to the movement.

    float dX, dY;
    
    @Override
    public boolean onTouchEvent(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 - (view.getWidth() / 2))
                    .y(event.getRawY() + dY - (view.getHeight() / 2))
                    .setDuration(0)
                    .start();
                break;
            default:
                return false;
        }
        return true;
    }
    

提交回复
热议问题