显示PopupWindow集中

时间:2011-05-19 19:07:05

标签: android android-layout popup

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

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

让窗口显示居中。

但我有另一个不是全屏的活动,当弹出窗口从正确的位置向下打开时。

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

我该怎么做?或者有一种更简单的方法可以让弹出窗口居中?

2 个答案:

答案 0 :(得分:103)

popupWindow.showAtLocation(anyViewOnlyNeededForWindowToken, Gravity.CENTER, 0, 0);

这将使您的观点居中。

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

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

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

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

我在这里写了Android PopupWindow.showAtLocation() and effects of Gravity

答案 1 :(得分:9)

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