改变视图背景颜色的奇怪问题

时间:2015-02-10 17:59:18

标签: android

我有一堆带有纯色背景的视图。这些观点可以被拖走;我想根据视图是否与另一个视图相交来更改背景。以下是我在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 个答案:

答案 0 :(得分: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);
        }
    }
}

我希望这会有所帮助。

相关问题