【问题标题】:Limit the movement of a view to prevent moving off the screen限制视图的移动以防止移出屏幕
【发布时间】:2018-06-17 14:41:41
【问题描述】:

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

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

【问题讨论】:

  • 请编辑您的标题,使其更明确。阅读How to ask
  • 抱歉我的问题的标题...但我不知道我的问题的正确名称。
  • 现在很好:)

标签: java android image ontouchlistener ontouch


【解决方案1】:

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

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

和相反的(xPosition &gt; 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;
    }
});

【讨论】:

  • 所以我会将if ( x &gt;= ( screenWidth/2) ) 替换为if( xPosition &lt; ScreenWidth-buffer ) { //run code to move object right } @TylerV
  • 你需要这两个条件,所以if( xPosition &lt; ScreenWidth-buffer &amp;&amp; x &gt;= (ScreenWidth/2))然后向右移动
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
相关资源
最近更新 更多