如何在坐标中获取视图的位置? [英] how to get view's position in coordinates?

查看:161
本文介绍了如何在坐标中获取视图的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我在RelativeLayout里面有一个ImageView,现在怎样才能在屏幕上获得imageview的X和Y位置?

Hi I have an ImageView inside RelativeLayout, now how can I get X and Y position of imageview on screen ?

我试过了

getLocationOnScreen
log(mPhoto.getLeft());
log(mPhoto.getScrollX());
log(mPhoto.getX());
log(mPhoto.getTranslationX());

但所有这些都返回0.

but all of them returns 0.

以上函数在逐步将imageview设置为中心后调用

Above functions are called after progmatically setting imageview to center

    RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(mFaceWidth, mFaceHeight);
    lp1.addRule(RelativeLayout.CENTER_HORIZONTAL);
    lp1.addRule(RelativeLayout.CENTER_VERTICAL);
    mPhoto.setLayoutParams(lp1);
    mPhoto.requestLayout();


推荐答案

查看树观察者回调将在视图后调用已在屏幕上呈现。上面的方法总是会产生0,因为尚未呈现视图/布局。

View Tree Observer callback will be called after the view has been rendered on screen. Above methods will always yield 0 as view/layout has not been rendered yet.

ViewTreeObserver vto=view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
@Override public void onGlobalLayout(){
  int [] location = new int[2];
  view.getLocationOnScreen(location);
  x = location[0];
  y = location[1];
  view.getViewTreeObserver().removeGlobalOnLayoutListener(this);

}
}

这篇关于如何在坐标中获取视图的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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