显示PopupWindow集中

Mar*_*los 43 android popup android-layout

我的应用程序上有一些弹出窗口,它是全屏和以下代码:

    content.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    content.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    int screenWidth = windowManager.getDefaultDisplay().getWidth();
    int screenHeight = windowManager.getDefaultDisplay().getHeight();
    int x = screenWidth / 2 - content.getMeasuredWidth() / 2;
    int y = screenHeight / 2 - content.getMeasuredHeight() / 2;
    window.showAtLocation(content, Gravity.NO_GRAVITY, x, y);
Run Code Online (Sandbox Code Playgroud)

使窗口显示居中.

但是我有另一个不是全屏的活动,当弹出窗口打开时它从需要的位置向右下方.

试图弄清楚为什么会发生这种情况,我认为showAtLocation显示它相对于当前的Activity,但我需要相对于显示器显示它.

我怎样才能做到这一点?或者有一种更简单的方法可以让弹出窗口居中?

Bae*_*Bae 107

popupWindow.showAtLocation(anyViewOnlyNeededForWindowToken, Gravity.CENTER, 0, 0);
Run Code Online (Sandbox Code Playgroud)

这将使您的视图居中.

我花了2个小时的痛苦来解决这个问题.我不需要任何黑魔法数学来处理这个问题.

窗口令牌只需要视图,它对位置没有其他影响.

重力告诉布局管理器在哪里启动坐标系以及如何处理这些坐标.我找不到文档,但黑客向我显示:

  • CENTER使用弹出窗口的中间部分与指定的x,y对齐.因此0,0以屏幕为中心
  • BOTTOM使用弹出窗口的底部与指定的x,y对齐.所以0,0的弹出底部与屏幕底部对齐.如果你想要10px填充然后y = 10(而不是-10),则将弹出窗口向上移动10个像素.

我在这里写了这个Android PopupWindow.showAtLocation()和Gravity的效果


小智 10

        View popupView = layoutInflater.inflate(R.layout.index_popviewxml,
                null);


        final PopupWindow popupWindow = new PopupWindow(popupView,
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, true);



        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);

        popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
Run Code Online (Sandbox Code Playgroud)