How to show PopupWindow at special location?

Eugene picture Eugene · Sep 17, 2011 · Viewed 58.5k times · Source

I need to show PopupWindow under one Views shown on the screen.

How can I calculate coordinates of needed View and place PopupWindow under it? Code example are more than welcome. Thanks.

Answer

zeetoobiker picture zeetoobiker · Sep 21, 2011

Locating an already displayed view is fairly easy - here's what I use in my code:

public static Rect locateView(View v)
{
    int[] loc_int = new int[2];
    if (v == null) return null;
    try
    {
        v.getLocationOnScreen(loc_int);
    } catch (NullPointerException npe)
    {
        //Happens when the view doesn't exist on screen anymore.
        return null;
    }
    Rect location = new Rect();
    location.left = loc_int[0];
    location.top = loc_int[1];
    location.right = location.left + v.getWidth();
    location.bottom = location.top + v.getHeight();
    return location;
}

You could then use code similar to what Ernesta suggested to stick the popup in the relevant location:

popup.showAtLocation(parent, Gravity.TOP|Gravity.LEFT, location.left, location.bottom);

This would show the popup directly under the original view - no guarantee that there would be enough room to display the view though.