Get position of ImageView relative to screen programmatically

Use View.getLocationOnScreen() or getLocationInWindow() BUT ONLY after the view has been layout. getTop(), getLeft(), getBottom() and getRight() return the position relative to its parent.


You need to wait for the callback when the layout has been placed with children views. This is the listener you need to add to your root view in order to calculate the coordinates for your image. Otherwise it will return 0.

getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        getViewTreeObserver().removeGlobalOnLayoutListener(this);

        int[] locations = new int[2];
        image.getLocationOnScreen(locations);
        int x = locations[0];
        int y = locations[1];
    }
});