Show a PopupWindow centralized(显示一个 PopupWindow 集中)
问题描述
I have some popups on my app, it's fullscreen and the following code:
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);
Make the window show centered.
But I have another Activity which is not fullscreen, when the popup opens it's right-down from where it's need to be.
Trying to figure out why this happens, I think the showAtLocation shows it's relative to the current Activity, but I need to show it relative to the display.
How can I do that? Or there's a simpler way to just the popup just centered?
popupWindow.showAtLocation(anyViewOnlyNeededForWindowToken, Gravity.CENTER, 0, 0);
This will center your view.
It took me 2 hours of pain to figure this out. I didn't need any black magic maths to handle this.
The view is only needed for the window token, it has no other impact on the location.
Gravity tells the layout manager where to start the coordinate system and how to treat those coordinates. I can't find the docs but hacking is showing me that:
- CENTER uses the middle of the popup to be aligned to the x,y specified. So 0,0 is screen centered
- BOTTOM uses the bottom of the popup to be aligned to the x,y specified. So 0,0 has the popup bottom aligned with the screen bottom. If you want 10px padding then y=10 (not -10) to move the popup up the screen 10 pixels.
I wrote this up over here Android PopupWindow.showAtLocation() and effects of Gravity
这篇关于显示一个 PopupWindow 集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:显示一个 PopupWindow 集中
基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01