Show a PopupWindow centralized

AndroidAndroid LayoutPopup

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcos VasconcelosView Question on Stackoverflow
Solution 1 - AndroidBaeView Answer on Stackoverflow
Solution 2 - Androiduser3921752View Answer on Stackoverflow