【问题标题】:How to show PopupWindow at special location?如何在特殊位置显示 PopupWindow?
【发布时间】:2011-09-16 22:18:53
【问题描述】:

我需要在屏幕上显示的Views 下显示PopupWindow

如何计算所需View 的坐标并将PopupWindow 置于其下?代码示例非常受欢迎。谢谢。

【问题讨论】:

    标签: android popupwindow


    【解决方案1】:

    定位已显示的视图相当容易 - 这是我在代码中使用的:

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

    然后您可以使用类似于 Ernesta 建议的代码将弹出窗口粘贴在相关位置:

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

    这将直接在原始视图下方显示弹出窗口 - 但不能保证有足够的空间来显示视图。

    【讨论】:

    • +1 表示这段非常有用的代码。对不起,我不能做更多;)
    • +1 只需要添加一些东西,首先最好只使用 Gravity.NO_GRAVITY,然后如果你想有一个边距,这样弹出窗口就不会在边缘您可以减去(例如 location.left - 50)。请记住,使用 location.right 时,您需要测量弹出窗口的宽度。对于弹出窗口测量,请访问此处stackoverflow.com/questions/15862052/…。带边距窗口的最终代码:location.left - popUpWindowWidth - 50
    • 此解决方案是否适用于 RTL 布局?如果不是,需要进行哪些修改才能使其适用于从右到左的配置?
    • @ A. B. 您需要处理 RTL 的条件。以上反映了两种布局的相同之处,即 RTL 和 LTR。
    • @zeetoobiker 您的解决方案运行完美!但我在弹出窗口中使用 SwitcherView。因此,在切换视图后,它正在改变弹出窗口的位置。有什么想法吗?
    【解决方案2】:

    你有getLeft()getBottom() 来获取视图在布局中的确切位置。您还可以通过getWidth()getHeight() 了解视图占用的确切空间。如果要将弹出窗口放置在视图下方。

    您使用视图的setLeft()setTop() 方法来定位新的弹出窗口。

    【讨论】:

    • 你能举个例子吗?
    【解决方案3】:

    要获取主应用程序屏幕的大小,而不需要标题和通知栏等内容,请在生成相关屏幕的类中覆盖以下方法(大小以像素为单位):

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

    获取要在其下显示弹出窗口的视图的底部坐标:

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

    现在只要height - coordinate 足够大以容纳您的弹出视图,您就可以像这样简单地放置弹出窗口:

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

    这里,showAtLocation() 将父视图与重力和位置偏移一起作为参数。

    【讨论】:

    • 这仅在button 位于屏幕中间时有效。即使我手动设置offset,这也不适用于不同的屏幕尺寸。
    • button 可以无处不在。
    • 等待 - 所以我提出的解决方案会在您的按钮下方显示弹出窗口。如果您将按钮放低,弹出窗口也会显示得较低。而且由于我认为弹出窗口占据了整个屏幕的宽度,因此按钮是否水平居中并不重要。还是我在这里遗漏了什么?
    • 很好,View.getBottom()。但是代码中有一个小问题。我已在编辑部分添加了该更改
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多