Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Gravity values effect PopupWindow.showAtLocation() in Android

Tags:

android

How do the different Gravity values effect PopupWindow.showAtLocation() in Android?

I can't find good docs on PopupWindows showAtLocation and Gravity.

like image 847
Bae Avatar asked Sep 16 '11 05:09

Bae


1 Answers

After hacking for a few hours trying some black magic maths to calculate centers and try to align the view using Gravity.TOP I found a post that used Gravity.CENTER. I'm collecting my findings here in the hopes it saves someone else some pain.

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

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, with no adjustments for the size of the notification bar.

Gravity.CENTER 0,0

  • 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.

Gravity.BOTTOM 0,10

  • TOP uses the top of the popup to be aligned to the x,y specified. So 0,0 has the popup top aligned with the screen top. If you want 10px padding then y=10. NOTE If you are not in full screen mode then you must also make adjustments for the notification bar.

Gravity.TOP 0,48

  • Gravity.LEFT and Gravity.RIGHT should be obvious now, for my example images they are too big to fit on the screen so they are clamped to the screen size minus the padding I am using.
like image 80
Bae Avatar answered Sep 22 '22 18:09

Bae