限制视图的移动以防止移出屏幕

Limit the movement of a view to prevent moving off the screen

我目前有一张图像可以向左或向右移动,具体取决于用户触摸设备屏幕的左侧还是右侧。但是,我不希望用户将图像移出屏幕!所以我想知道,我可以限制或限制用户可以向左或向右移动图像的距离吗? 这是移动图像的代码(当设备屏幕的左侧或右侧被触摸时)

   //OnTouch Function
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            int x = (int)event.getX();
            if ( x >= ( screenWidth/2) ) {
                int ScreenWidth = getResources().getDisplayMetrics().widthPixels;
                float Xtouch = event.getRawX();
                int sign = Xtouch > 0.5 * ScreenWidth ? 1 : -1;
                float XToMove = 85;
                int durationMs = 50;
                v.animate().translationXBy(sign*XToMove).setDuration(durationMs);
            }else {
                if( x < ( screenWidth/2) ) {
                    int ScreenWidth = getResources().getDisplayMetrics().widthPixels;
                    float xtouch = event.getRawX();
                    int sign = xtouch < 0.5 / ScreenWidth ? 1 : -1;
                    float xToMove = 60; // or whatever amount you want
                    int durationMs = 50;
                    v.animate().translationXBy(sign*xToMove).setDuration(durationMs);
                }
            }
            return false;
        }
    });

只需跟踪对象的 xPosition(add/subtract 从 class 变量每次移动)在移动对象之前添加一个检查。如

if( xPosition < ScreenWidth-buffer ) {
    //run code to move object right
}

和相反的 (xPosition > buffer) 在将图像向左移动的代码中,缓冲区是您想要在屏幕边缘的一些边距。例如:

private float xPosition; // set to initial position in onCreate

//OnTouch Function
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        float x = event.getRawX();
        int durationMs = 50;
        int buffer = 90;
        if ( x >= ( screenWidth/2) && xPosition < screenWidth-buffer ) {
            float XToMove = 85;
            v.animate().translationXBy(XToMove).setDuration(durationMs);
            xPosition += XToMove;
        }else if( x < ( screenWidth/2) && xPosition > buffer ) {
            float XToMove = -60; // or whatever amount you want
            v.animate().translationXBy(XToMove).setDuration(durationMs);
            xPosition += XToMove;
        }
        return false;
    }
});