改变视图背景颜色的奇怪问题
问题描述:
我有一堆纯色背景的意见。这些观点可以拖动;我想根据视图是否与另一个视图相交来更改背景。下面是我使用的代码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
带来了“前”的感动,所以用户可以很容易地操纵它,如果它隐藏在另一个视图之后。下面介绍它目前是如何工作的:
这些视图布局使用RelativeLayout
。我开始认为这些观点的排序可能是这个原因,但我不确定。
答
在我看来,您需要稍微修改for
循环。原因是因为如果childOne
与childTwo
相交,则表示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);
}
}
}
我希望这有助于。
感谢您的提示!我相信我也了解了这个问题。在循环视图时,如果视图不与视图相交,则无论视图是否已与其他视图相交,它都将变为绿色。我需要找到解决办法。 – Raggeth 2015-02-10 21:56:50
@Raggeth我其实并没有考虑你刚刚提到的情况。 – iRuth 2015-02-10 21:59:21