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