How do the different Gravity values effect PopupWindow.showAtLocation() in Android?
I can't find good docs on PopupWindows showAtLocation and Gravity.
How do the different Gravity values effect PopupWindow.showAtLocation() in Android?
I can't find good docs on PopupWindows showAtLocation and Gravity.
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:
You can change the gravity of a PopupWindow
by adjusting Gravity.CENTER
in the showAtLocation
method:
popupWindow.showAtLocation(anyView, Gravity.CENTER, 0, 0);
The images below show the effects:
Gravity.CENTER
Gravity.TOP
Gravity.BOTTOM
Gravity.LEFT
Gravity.RIGHT
Gravity.TOP | Gravity.LEFT
Gravity.TOP | Gravity.RIGHT
Gravity.BOTTOM | Gravity.LEFT
Gravity.BOTTOM | Gravity.RIGHT
You can further position it by changing the (x,y)
offsets in
popupWindow.showAtLocation(anyView, gravity, x, y);
For example
popupWindow.showAtLocation(anyView, Gravity.BOTTOM, 0, 300);
Here is the code for the examples above. See How to make a simple Android popup window for more basic help.
int gravity = Gravity.CENTER;
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.popup_window, null);
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true;
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
popupView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
popupWindow.showAtLocation(anyView, gravity, 0, 0);
showAsDropDown
if you want to anchor the popup to a view.© 2022 - 2024 — McMap. All rights reserved.