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

时间:2018-06-17 14:41:41

标签: java android image ontouchlistener ontouch

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

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

1 个答案:

答案 0 :(得分:1)

只需跟踪对象的xPosition(每次移动时从类变量中加/减)在移动对象之前在其中添加一个检查。如在

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