我想以编程方式获取 View 的 X 或 Y 位置(即按钮),但是 在链接( https://blog.takescoop.com/android-view-measurement-d1f2f5c98f75 )的解决方案中返回的值是错误的。
我需要这个来限制动画中的 y 以实现夹紧功能。
此外,我在以编程方式获取高度和宽度时遇到问题。我可以像这里一样获取 View ( https://stackoverflow.com/a/24035591/9498656 by view.post(new Runnable()) 但就像以前一样,值(value)观是错误的。
problem: animated view with restrictions on other view Y
有人可以解释一下如何获取不同屏幕的 X Y 高度宽度吗?
最佳答案
获取相对于您可以使用的设备屏幕的 View 的 posX 和 posX;
int location[] = new int[2];
view.getLocationOnScreen(location);
int posX = location[0];
int posY = location[1];
要获取 View 的高度和宽度,您可以使用
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
view.getHeight(); //height is ready
view.getWidth(); //width is ready
}
});
不要忘记通过调用 view.getViewTreeObserver().removeOnGlobalLayoutListener(this); 来删除 ViewTreeObser 的监听器到您的 View
关于java - 无论设备屏幕大小如何,如何获取添加 View 的位置 X、Y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49305464/