[英]How to avoid Android button dragging out side the screen
i have implemented button drag in my application , but it working the problem is why am dragging button is going out side of side am not able see the button. 我已经在我的应用程序中实现了按钮拖动,但它解决了问题是为什么我拖动按钮走出侧面我无法看到按钮。 but fix it. 但要解决它。 i need to drag side the the screen. 我需要拖动屏幕。 i have tried below code if any wrong correct me, 我试过下面的代码,如果有任何错误纠正我,
@Override
public boolean onTouch(View v, MotionEvent event)
{
final int d_X = (int) event.getRawX();
final int d_Y = (int) event.getRawY();
PointF start = new PointF();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
start.set(event.getX(),event.getY());
if(shouldAllowToDrag) // if it true then i will allow to drag.
{
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
_xDelta = d_X - lParams.leftMargin;
_yDelta = d_Y - lParams.topMargin;
}
else
{
//check for double click
long pressTime = System.currentTimeMillis();
// If double click...
String buttonTitle = moveButton.getText().toString();
if (pressTime - lastPressTime <= DOUBLE_PRESS_INTERVAL) {
Log.i(TAG,"doubleTappedistrue");
hasLatchedDown = false;
if(buttonTitle.equals("Unlocked"))
{
hasButtonUnlocked = false;
moveButton.setText("Locked");
}
else if(buttonTitle.equals("Locked"))
{
hasButtonUnlocked = true;
moveButton.setText("Unlocked");
}
}
else
{
hasLatchedDown = true;
buttonLastStateText = buttonTitle;
moveButton.setText("Unlocked");
}
lastPressTime = pressTime;
}
break;
case MotionEvent.ACTION_UP:
if(!shouldAllowToDrag)
{
if(hasLatchedDown)
{
hasLatchedDown = false;
moveButton.setText(buttonLastStateText);
}
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
if(shouldAllowToDrag){
View parentView = (View) v.getParent();
parentView.getWidth();
parentView.getHeight();
imageView.getWidth();
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
layoutParams.leftMargin = d_X - _xDelta;
layoutParams.topMargin = d_Y - _yDelta;
v.setLayoutParams(layoutParams);
}
break;
}
return true;
}
You should add a min/max check: 您应该添加最小/最大检查:
layoutParams.leftMargin = Math.min(Math.max(d_X - _xDelta,0), parentView.getWidth() - layoutParams.width);
Same idea for the topMargin. topMargin也是一样的想法。 (code not compile checked) Let me know if this helped. (代码未编译检查)让我知道这是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.