大佬教程收集整理的这篇文章主要介绍了android – 在父边界内限制子视图,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在创建一个矩形框并在其中放置一个可以移动的imageView.在做onMove的时候,我注意到imageView已经超出了我不想要的父视图的边界.我想在它的父视图的边界内限制imageView.怎么做.
这是xml:
<FrameLayout
android:layout_width="400dp"
android:layout_height="400dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="@+id/objContainer"
android:BACkground="@android:color/holo_blue_bright" >
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/btn_default" />
</FrameLayout>
</RelativeLayout>
和handletouch事件的代码:
@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;
}}
解决方法:
在重写的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本身无效.
以上是大佬教程为你收集整理的android – 在父边界内限制子视图全部内容,希望文章能够帮你解决android – 在父边界内限制子视图所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。