Skip to content Skip to sidebar Skip to footer

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.getScr

Solution 1:

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 publicvoidonGlobalLayout(){
  int [] location = newint[2];
  view.getLocationOnScreen(location);
  x = location[0];
  y = location[1];
  view.getViewTreeObserver().removeGlobalOnLayoutListener(this);

}
}

Solution 2:

Try this

view.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {
            Log.i("trace", "Y: " + v.getY());
        }
    });

Clicking the image view will print visual Y position of view in logcat.

Solution 3:

try this :

int [] location = newint[2];
view.getLocationOnScreen(location);
x = location[0];
y = location[1];

Solution 4:

It was not yet measured so I used following How can you tell when a layout has been drawn?

finalLinearLayoutlayout= (LinearLayout)findViewById(R.id.YOUR_VIEW_ID);
ViewTreeObservervto= layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(newOnGlobalLayoutListener() { 
    @OverridepublicvoidonGlobalLayout() { 
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        intwidth= layout.getMeasuredWidth();
        intheight= layout.getMeasuredHeight(); 
        intx= layout.getX();
        inty= layout.getY();

    } 
});

Post a Comment for "How To Get View's Position In Coordinates?"