Android 限制父边界内的子视图
我正在创建一个矩形框,并在其中放置一个可以移动的imageView。在进行onMove时,我注意到imageView超出了它的父视图的范围,这是我不想要的。我想将imageView限制在其父视图的边界内。如何做到这一点 以下是xml:Android 限制父边界内的子视图,android,android-layout,Android,Android Layout,我正在创建一个矩形框,并在其中放置一个可以移动的imageView。在进行onMove时,我注意到imageView超出了它的父视图的范围,这是我不想要的。我想将imageView限制在其父视图的边界内。如何做到这一点 以下是xml: 在被覆盖的onTouch中,您需要检查以下移动是否会将ImageView保留在其容器中 换句话说,您需要检查在被dx,dy移动后,ImageView的矩形是否会留在父对象内 下面是一个例子: case MotionEvent.ACTION_MOVE: .
在被覆盖的
onTouch
中,您需要检查以下移动是否会将ImageView
保留在其容器中
换句话说,您需要检查在被dx,dy移动后,ImageView
的矩形是否会留在父对象内
下面是一个例子:
case MotionEvent.ACTION_MOVE:
...
// Calculate the distance moved
final float dx = x1 - mLastTouchX;
final float dy = y1 - mLastTouchY;
// Make sure we will still be the in parent's container
Rect parent = new Rect(0, 0, root.getWidth(), root.getHeight());
int newLeft = (int) (iv.getX() + dx),
newTop = (int) (iv.getY() + dy),
newRight = newLeft + iv.getWidth(),
newBottom = newTop + iv.getHeight();
if (!parent.contains(newLeft, newTop, newRight, newBottom)) {
Log.e(TAG, String.format("OOB @ %d, %d - %d, %d",
newLeft, newTop, newRight, newBottom));
break;
}
...
还要注意的是,您不需要使容器无效,因为setX/setY会使
ImageView
本身无效。工作起来很有魅力。谢谢。你能告诉我我们想要在边界内拖动一个视图吗,这样一旦父视图和子视图边界匹配,它就不会移动。这段代码中的mPosX是什么?
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
final float x = event.getRawX();
final float y = event.getRawY();
// Remember where we started
mLastTouchX = x;
mLastTouchY = y;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
final float x1 = event.getRawX();
final float y1 = event.getRawY();
// Calculate the distance moved
final float dx = x1 - mLastTouchX;
final float dy = y1 - mLastTouchY;
// Move the object
mPosX += dx;
mPosY += dy;
view.setX(mPosX);
view.setY(mPosY);
// Remember this touch position for the next move event
mLastTouchX = x1;
mLastTouchY = y1;
// Invalidate to request a redraw
root.invalidate();
break;
}
return true;
}}
case MotionEvent.ACTION_MOVE:
...
// Calculate the distance moved
final float dx = x1 - mLastTouchX;
final float dy = y1 - mLastTouchY;
// Make sure we will still be the in parent's container
Rect parent = new Rect(0, 0, root.getWidth(), root.getHeight());
int newLeft = (int) (iv.getX() + dx),
newTop = (int) (iv.getY() + dy),
newRight = newLeft + iv.getWidth(),
newBottom = newTop + iv.getHeight();
if (!parent.contains(newLeft, newTop, newRight, newBottom)) {
Log.e(TAG, String.format("OOB @ %d, %d - %d, %d",
newLeft, newTop, newRight, newBottom));
break;
}
...