android: move a view on touch move (ACTION_MOVE)

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

    The same as @Alex Karshin's answer, I change a bit.

    public class MovingObject implements OnTouchListener {
    private RelativeLayout.LayoutParams lParams;
    private PointF viewPoint, prePoint, currPoint;
    
    public MovingObject() {
        lParams = null;
        viewPoint = new PointF();
        prePoint = new PointF();
        currPoint = new PointF();
    }
    
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            viewPoint.set(view.getX(), view.getY());
            prePoint.set(event.getRawX(), event.getRawY());
            lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            break;
        case MotionEvent.ACTION_UP:
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            break;
        case MotionEvent.ACTION_POINTER_UP:
            break;
        case MotionEvent.ACTION_MOVE:
            currPoint.set(event.getRawX(), event.getRawY());
            moveToCurrentPoint(view);
            break;
        }
        view.invalidate();
        return true;
    }
    
    private void moveToCurrentPoint(View view) {
        float dx = currPoint.x - prePoint.x - prePoint.x + viewPoint.x;
        float dy = currPoint.y - prePoint.y - prePoint.y + viewPoint.y;
        lParams.leftMargin = (int) (prePoint.x + dx);
        lParams.topMargin = (int) (prePoint.y + dy);
        view.setLayoutParams(lParams);
    }
    }
    

提交回复
热议问题