获取视图相对于根布局的坐标 [英] Getting View's coordinates relative to the root layout

查看:38
本文介绍了获取视图相对于根布局的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能否在 Android 中获取视图的 x 和 y 相对于我的 Activity 的根布局的位置?

Can I get a View's x and y position relative to the root layout of my Activity in Android?

推荐答案

这是一种解决方案,但由于 API 会随着时间的推移而变化,而且可能还有其他方法,请务必查看其他答案.一个声称更快,另一个声称更容易.

This is one solution, though since APIs change over time and there may be other ways of doing it, make sure to check the other answers. One claims to be faster, and another claims to be easier.

private int getRelativeLeft(View myView) {
    if (myView.getParent() == myView.getRootView())
        return myView.getLeft();
    else
        return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}

private int getRelativeTop(View myView) {
    if (myView.getParent() == myView.getRootView())
        return myView.getTop();
    else
        return myView.getTop() + getRelativeTop((View) myView.getParent());
}

让我知道这是否有效.

它应该递归地添加每个父容器的顶部和左侧位置.如果需要,您也可以使用 Point 实现它.

It should recursively just add the top and left positions from each parent container. You could also implement it with a Point if you wanted.

这篇关于获取视图相对于根布局的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆