拖动按钮移出屏幕了吗? [英] Dragging button is going out of the screen?
问题描述
我有一个按钮,可以将其拖动到屏幕上的任何位置,但是拖动时它在屏幕外,所以如何只在屏幕内拖动,这样它就不会超出屏幕
I have one button and i can drag it anywhere on the screen, but it is going outside the screen while dragging, so how to drag only inside the screen, so that it should not go out of the screen
Button.setOnTouchListener(new TextView.OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
X_button = (int) event.getRawX();
Y_button= (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
_xDelta = X_button - lParams.leftMargin;
_yDelta = Y_button - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
if(!isMoving)
{
view.performClick();
}
isMoving=false;
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
isMoving=true;
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
.getLayoutParams();
layoutParams.leftMargin = X_button - _xDelta;
layoutParams.topMargin = Y_button - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
break;
}
return true;
}
});
推荐答案
首先,使用方法View.setX()
,View.setY()
,View.setTranslateX()
,View.setTranslateY()
在屏幕上移动视图,而不是更新LayoutParams的边距.我发现它们的执行方式更流畅.
First, use the methods View.setX()
, View.setY()
, View.setTranslateX()
, View.setTranslateY()
for moving Views on screen instead of updating margins of LayoutParams. I've found them to perform way more smoother.
第二,为了将视图限制为可用窗口,请使用以下功能获取可用窗口的大小:
Second, for limiting the views to your available window, get the available window size using the following function:
DisplayMetrics metrics = getResources().getDisplayMetrics();
int windowWidth = metrics.widthPixels;
int windowHeight = metrics.heightPixels
接下来,在您的onTouch方法中,计算目标位置是否超过上述尺寸.例如:
Next, in your onTouch method, calculate if the target location exceeds the above dimensions. For example:
if( currentXLocation + deltaX > windowWidth ){
// this will ensure that target location
// is always <= windowHeight
deltaX = windowWidth - currentXLocation;
} else if( currentXLocation + deltaX < 0){
deltaX = -(currentXLocation);
} else if (...){
// perform similar calculations for the rest
}
这篇关于拖动按钮移出屏幕了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!