Q
检测视图是否重叠
8
A
回答
14
Berserk感谢你的帮助! 经过一番实验,我写了检测视图重叠与否的方法!
private boolean isViewOverlapping(View firstView, View secondView) {
int[] firstPosition = new int[2];
int[] secondPosition = new int[2];
firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
firstView.getLocationOnScreen(firstPosition);
secondView.getLocationOnScreen(secondPosition);
int r = firstView.getMeasuredWidth() + firstPosition[0];
int l = secondPosition[0];
return r >= l && (r != 0 && l != 0);
}
3
10
您还可以使用Rect.intersect()查找重叠视图。
int[] firstPosition = new int[2];
int[] secondPosition = new int[2];
firstView.getLocationOnScreen(firstPosition);
secondView.getLocationOnScreen(secondPosition);
// Rect constructor parameters: left, top, right, bottom
Rect rectFirstView = new Rect(firstPosition[0], firstPosition[1],
firstPosition[0] + firstView.getMeasuredWidth(), firstPosition[1] + firstView.getMeasuredHeight());
Rect rectSecondView = new Rect(secondPosition[0], secondPosition[1],
secondPosition[0] + secondView.getMeasuredWidth(), secondPosition[1] + secondView.getMeasuredHeight());
return rectFirstView.intersect(rectSecondView);
+0
这对我有效,谢谢! – APengue 2016-09-25 04:37:33
+0
这是唯一对我有用的答案。谢谢 – 2017-04-22 16:50:48
1
这与Marcel Derks的答案类似,但是不需要额外的导入。它使用形成Rect.intersect
而不创建Rect
对象的基本代码。
private boolean isViewOverlapping(View firstView, View secondView) {
int[] firstPosition = new int[2];
int[] secondPosition = new int[2];
firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
firstView.getLocationOnScreen(firstPosition);
secondView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
secondView.getLocationOnScreen(secondPosition);
return firstPosition[0] < secondPosition[0] + secondView.getMeasuredWidth()
&& firstPosition[0] + firstView.getMeasuredWidth() > secondPosition[0]
&& firstPosition[1] < secondPosition[1] + secondView.getMeasuredHeight()
&& firstPosition[1] + firstView.getMeasuredHeight() > secondPosition[1];
}
您不需要强制视图测量,但它的好办法做;)
尝试使用不同的布局 – Pr38y 2014-10-08 08:49:05
您使用的是不同的屏幕分辨率不同的布局? – 2014-10-08 08:50:17
我不能改变布局,这是客户的愿望! – smail2133 2014-10-08 08:50:35