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

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

问题描述

我可以得到一个视图的x和y位置相对于我的活动在Android的根布局?

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

推荐答案

这是一个解决方案,但由于原料药随着时间的推移而变化有可能是做这件事的其他方式,请务必检查其他答案。一个自称是更快,而另一索赔更容易。

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());
}

让我知道,如果工程。

这应该递归只是从每个父容器中添加顶部和左侧位置。 你也可以用它执行如果你想要的。

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天全站免登陆