2015-02-10 54 views
0

我有一堆純色背景的意見。這些觀點可以拖動;我想根據視圖是否與另一個視圖相交來更改背景。下面是我使用的代碼MotionEvent.ACTION_UP改變視圖背景顏色的奇怪問題

// Get all children of the parent view 
for(int i = 0; i < ((ViewGroup) getParent()).getChildCount(); i++) { 
    View childOne = ((ViewGroup) getParent()).getChildAt(i); 
    // For each child, check for intersection with siblings 
    for(int z = 0; z < ((ViewGroup) getParent()).getChildCount(); z++) { 
     View childTwo = ((ViewGroup) getParent()).getChildAt(z); 
     if(childOne == childTwo) 
      continue; 
     Rect recOne = new Rect(); 
     childOne.getHitRect(recOne); 
     Rect recTwo = new Rect(); 
     childTwo.getHitRect(recTwo); 
     if (Rect.intersects(recOne, recTwo)) { 
      ((EditView) childTwo).setPaintColor(Color.RED); 
     } else { 
      ((EditView) childTwo).setPaintColor(Color.GREEN); 
     } 
    } 
} 

這應該遍歷每個視圖,並檢查視圖與另一個視圖相交。如果是這樣,請更改交叉視圖的背景顏色。所有視圖都擴展了EditView類,該類處理自己的觸摸事件。我還應該提到,MotionEvent.ACTION_DOWN帶來了「前」的感動,所以用戶可以很容易地操縱它,如果它隱藏在另一個視圖之後。下面介紹它目前是如何工作的:

example

這些視圖佈局使用RelativeLayout。我開始認爲這些觀點的排序可能是這個原因,但我不確定。

回答

1

在我看來,您需要稍微修改for循環。原因是因爲如果childOnechildTwo相交,則表示childTwo也與childOne相交,(因此不需要檢查兩次)。由於兩個視圖相交,我會同時更改兩個視圖的顏色。所以我會這樣修改你的代碼:

// Get all children of the parent view 
for(int i = 0; i < ((ViewGroup) getParent()).getChildCount(); i++) { 
    View childOne = ((ViewGroup) getParent()).getChildAt(i); 
    // For each child, check for intersection with siblings 
    // start z at index (i+1) 
    for(int z = i+1; z < ((ViewGroup) getParent()).getChildCount(); z++) { 
     View childTwo = ((ViewGroup) getParent()).getChildAt(z); 
     Rect recOne = new Rect(); 
     childOne.getHitRect(recOne); 
     Rect recTwo = new Rect(); 
     childTwo.getHitRect(recTwo); 
     if (Rect.intersects(recOne, recTwo)) { 
      // both views intersect, change both to red 
      ((EditView) childOne).setPaintColor(Color.RED); 
      ((EditView) childTwo).setPaintColor(Color.RED); 
     } else { 
      // both views do not intersect, change both to green 
      ((EditView) childOne).setPaintColor(Color.GREEN); 
      ((EditView) childTwo).setPaintColor(Color.GREEN); 
     } 
    } 
} 

我希望這有助於。

+0

感謝您的提示!我相信我也瞭解了這個問題。在循環視圖時,如果視圖不與視圖相交,則無論視圖是否已與其他視圖相交,它都將變爲綠色。我需要找到解決辦法。 – Raggeth 2015-02-10 21:56:50

+0

@Raggeth我其實並沒有考慮你剛剛提到的情況。 – iRuth 2015-02-10 21:59:21