如何在坐标中获取视图的位置?

问题描述:

嗨我在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);

}
}