我想只在Y方向拖放一个按钮。我实现了这个功能。但它跨越屏幕边界并消失了。请帮助我实现目标。
这是我的代码
public class ChoiceTouchListener implements View.OnTouchListener{
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int x = (int) motionEvent.getRawX();
int y = (int) motionEvent.getRawY();
DisplayMetrics metrics = getResources().getDisplayMetrics();
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams tparams = (RelativeLayout.LayoutParams) view.getLayoutParams();
changey = y- tparams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
params.topMargin = y-changey;
view.setLayoutParams(params);
break;
}
rootlayout.invalidate();
return true;
}
}
答案 0 :(得分:0)
您可以使用它来限制屏幕边界。
int width=cropperLayout.getLayoutParams().width;;
int height=cropperLayout.getLayoutParams().height;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
dX = v.getX() - event.getRawX();
dY = v.getY() - event.getRawY();
return true;
case MotionEvent.ACTION_MOVE:
if (width == windowWidth && height == windowHeight){}
else {
v.animate()
.x(event.getRawX() + dX)
.y(event.getRawY() + dY)
.setDuration(0)
.start();
if (event.getRawX() + dX + width > windowWidth) {
v.animate()
.x(windowWidth - width)
.setDuration(0)
.start();
}
if (event.getRawX() + dX < 0) {
v.animate()
.x(0)
.setDuration(0)
.start();
}
if (event.getRawY() + dY + height > windowHeight) {
v.animate()
.y(windowHeight - height)
.setDuration(0)
.start();
}
if (event.getRawY() + dY < 0) {
v.animate()
.y(0)
.setDuration(0)
.start();
}
return true;
}