Bound a View to drag inside RelativeLayout

前端 未结 3 1497
小鲜肉
小鲜肉 2021-01-04 22:36

I have created a draggable view inside RelativeLayout. But it seems to go beyond the RelativeLayout.

I simply

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-04 23:01

    In OnTouch you calculate where to move your view

    case MotionEvent.ACTION_MOVE:
                v.animate()
                        .x(event.getRawX() + dX)
                        .y(event.getRawY() + dY)
                        .setDuration(0)
                        .start();
    

    You should check the boundaries for x and y before moving it.

    case MotionEvent.ACTION_MOVE:
            float x = event.getRawX() + dX; float y = event.getRawY() + dY;
            if (x > boundaryRight) x = boundaryRight;
            else if (x < boundaryLeft) x = boundaryLeft;
            if (y < boundaryTop) y = boundaryTop;
            else if (y > boundaryBottom) y = boundaryBottom;
            v.animate()
                    .x(x)
                    .y(y)
                    .setDuration(0)
                    .start();
    

    And to calculate boundaries of your RelativeLayout at run-time you should use Runnable or a Listener or similar Determining the size of an Android view at runtime

提交回复
热议问题