Search code examples
androidimageviewandroid-relativelayout

how to get view's position in coordinates?


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

I have tried

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

but all of them returns 0.

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

Solution

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