gpt4 book ai didi

java - 限制 View 的移动以防止移出屏幕

转载 作者:行者123 更新时间:2023-12-02 11:06:48 26 4
gpt4 key购买 nike

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

   //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(每次移动时从类变量中添加/减去)在移动对象之前添加一个检查。如

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

以及向左移动图像的代码中的相反 (xPosition > buffer),其中 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;
}
});

关于java - 限制 View 的移动以防止移出屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com