gpt4 book ai didi

android - 显示一个 PopupWindow 集中

转载 作者:IT王子 更新时间:2023-10-28 23:55:52 29 4
gpt4 key购买 nike

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

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

使窗口居中显示。

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

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

我该怎么做?还是有更简单的方法让弹出窗口居中?

最佳答案

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

这将使您的 View 居中。

我花了 2 个小时的痛苦才弄清楚这一点。我不需要任何黑魔法数学来处理这个。

View 只需要window token,对位置没有其他影响。

重力告诉布局管理器从哪里开始坐标系以及如何处理这些坐标。我找不到文档,但黑客向我展示了这一点:

  • CENTER 使用弹出窗口的中间与指定的 x,y 对齐。所以 0,0 是屏幕居中的
  • BOTTOM 使用弹出窗口的底部与指定的 x,y 对齐。所以 0,0 使弹出窗口底部与屏幕底部对齐。如果您想要 10 像素的内边距,则 y=10(不是 -10)将弹出窗口向上移动 10 像素。

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

关于android - 显示一个 PopupWindow 集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063667/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com