ViewGroup如何按位置(x,y)获取子视图?

时间:2017-01-17 06:35:21

标签: java android view viewgroup

我正在制作CustomLayout,其中包含一些子视图。这些子视图可以彼此重叠。可以通过setRotation setScale等修改这些子视图的转换矩阵。

我们如何通过当地位置(x,y)吸引孩子?:

class CustomLayout extends ViewGroup {
    public View getChildByLocation(int x, int y) {
        // HOW TO IMPLEMENT THIS
    }
}

据我所知,到目前为止ViewGroup允许我们getChildAt(index)所以我可以循环其子项以找出我需要的视图。但它是如此复杂,我想要一个官方的方式来按位置(x,y)获得一个孩子。

提前谢谢!

1 个答案:

答案 0 :(得分:0)

请使用此Utils类。只需要一个方法调用

无需子类化您的布局。从主线程调用该方法,它也支持转换/旋转/缩放。

// return null if no child at the position is found
View outputView = Utils.findChildByPosition(theParentViewGroup, x, y)

类Utils的完整源代码:

public final class Utils {
    /**
     * find child View in a ViewGroup by its position (x, y)
     *
     * @param parent the viewgourp
     * @param x      the x position in parent
     * @param y      the y position in parent
     * @return null if not found
     */
    public static View findChildByPosition(ViewGroup parent, float x, float y) {
        int count = parent.getChildCount();
        for (int i = count - 1; i >= 0; i--) {
            View child = parent.getChildAt(i);
            if (child.getVisibility() == View.VISIBLE) {
                if (isPositionInChildView(parent, child, x, y)) {
                    return child;
                }
            }
        }

        return null;
    }

    private static boolean isPositionInChildView(ViewGroup parent, View child, float x, float y) {
        sPoint[0] = x + parent.getScrollX() - child.getLeft();
        sPoint[1] = y + parent.getScrollY() - child.getTop();

        Matrix childMatrix = child.getMatrix();
        if (!childMatrix.isIdentity()) {
            childMatrix.invert(sInvMatrix);
            sInvMatrix.mapPoints(sPoint);
        }

        x = sPoint[0];
        y = sPoint[1];

        return x >= 0 && y >= 0 && x < child.getWidth() && y < child.getHeight();
    }

    private static Matrix sInvMatrix = new Matrix();
    private static float[] sPoint = new float[2];
}