视图相对于父级的位置

时间:2018-01-25 19:31:40

标签: android android-layout coordinates

我使用Android 5.1创建了一个自定义视图,如下所示:

myRectangleView

现在我想得到 View rectangleView = findViewById(R.id.myRectangleView); rectangleView.getLocationOnScreen(location); int x = location[0]; int y = location[1]; 的x和y位置。我可以这样做:

task_header

问题在于,这给了我屏幕上的绝对位置,但我想要相对于{{1}}的位置。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以尝试遍历"向上"从每个视图中,总结过程中每个容器的位置:

/** Returns array of views [x, y] position relative to parent **/
public static int[] getPositionInParent(ViewGroup parent, View view){
    int relativePosition[] = {view.getLeft(), view.getTop()};
    ViewGroup currentParent = (ViewGroup) view.getParent();
    while (currentParent != parent){
        relativePosition[0] += currentParent.getLeft();
        relativePosition[1] += currentParent.getTop();
        currentParent = (ViewGroup) currentParent.getParent();
    }
    return relativePosition;
}

这没有错误处理,但即使在更多嵌套布局中也应该有效。

答案 1 :(得分:0)

我在Kotlin中实现了一个简单的方法。如果您知道子参数视图的直接父级,这将起作用。

        fun getPositionInParent(parent: ViewGroup, child: View): IntArray {
            val relativePosition = intArrayOf(child.left, child.top)
            val positionPreview = intArrayOf(1, 2)
            val positionFrame = intArrayOf(1, 2)
            parent.getLocationInWindow(positionPreview)
            child.getLocationInWindow(positionFrame)

            relativePosition[0] = positionFrame[0] - positionPreview[0]
            relativePosition[1] = positionFrame[1] - positionPreview[1]
            return relativePosition
        }