How to show PopupWindow at special location?

2020-01-27 10:06发布

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.

3条回答
▲ chillily
2楼-- · 2020-01-27 10:41

To get size of the main application screen without stuff like title and notification bars, override the following method in the class generating the screen in question (sizes are measured in pixels):

@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
}

To get the bottom coordinate of the view under which you want to show the popup:

View upperView = ...
int coordinate = upperView.getBottom();

Now as long as height - coordinate is large enough for your popup view, you can simply place the popup like this:

PopupWindow popup = new PopupWindow();

Button button = new Button(this);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        popup.showAtLocation(parent, Gravity.CENTER, 0, coordinate);
    }
});

Here, showAtLocation() takes the parent view as an argument together with gravity and location offsets.

查看更多
对你真心纯属浪费
3楼-- · 2020-01-27 10:49

you have getLeft() and getBottom() to get the exact position of the view in the layout. You also have getWidth() and getHeight() to know the exact space occupied by the view. If you want to position your popup window below a view.

You setLeft() and setTop() methods of the view to position the new popup Window.

查看更多
混吃等死
4楼-- · 2020-01-27 10:50

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.

查看更多
登录 后发表回答