简体   繁体   English

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

[英]ViewGroup How to get child view by location (x, y)?

I am making CustomLayout which can contain some child views. 我正在制作CustomLayout ,它可以包含一些子视图。 These child views may be overlapped each other. 这些子视图可以彼此重叠。 These child view's transform matrix be modified via setRotation setScale etc. 可以通过setRotation setScale等修改这些子视图的变换矩阵。

How we can get a child by local location (x, y)?: 我们如何通过当地位置(x,y)获得孩子?:

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

As I know so far ViewGroup allow us to getChildAt(index) so I can loop through its children to find out the view I need. 据我所知,到目前为止, ViewGroup允许我们使用getChildAt(index)这样我就可以遍历它的子节点来查找我需要的视图。 But it is so complicated and I want a official way to get a child by location(x,y). 但它是如此复杂,我想要一个官方的方式来获取一个孩子的位置(x,y)。

Thank you in advance! 先感谢您!

Use this Utils class bellow. 请使用下面的Utils类。 Only 1 method call needed 只需要1个方法调用

No need to subclass your layout. 无需子类化您的布局。 Call that method from main-thread, it supports translation/rotation/scale as well. 从主线程调用该方法,它也支持转换/旋转/缩放。

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

Full Source code of class Utils: 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM