2014-10-08 106 views
8

我在另一個尺寸屏幕上繪製視圖時遇到問題! 我需要具有View類型兩個參數的方法。如果第一個視圖重疊在第二個視圖上,則返回true,在另一個視圖中返回false!檢測視圖是否重疊

enter image description here

enter image description here

+0

嘗試使用不同的佈局 – Pr38y 2014-10-08 08:49:05

+0

您使用的是不同的屏幕分辨率不同的佈局? – 2014-10-08 08:50:17

+0

我不能改變佈局,這是客戶的願望! – smail2133 2014-10-08 08:50:35

回答

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); 
    } 
+0

好的工作...... :) – berserk 2014-10-10 08:25:45

+0

這是否涵蓋了所有的角落? – 2015-01-12 09:32:22

+0

是的,但我不檢查它。這個解決方案對我有好處。試試你。 – smail2133 2015-01-12 09:37:40

3

好像你所要求的代碼,你的問題。我發佈了我認爲可能工作的邏輯:

  1. 創建一個函數,它將兩個視圖作爲參數,並返回一個布爾值。
  2. 現在使用this檢查屏幕上兩個視圖的位置。它會讓你知道它們是否重疊。
  3. 根據它返回true或false。
+0

謝謝你的回覆!我會試着像你說的那樣執行。如果解決方案能夠運行良好,我會在這裏寫代碼! – smail2133 2014-10-09 09:09:57

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]; 
} 

您不需要強制視圖測量,但它的好辦法做;)