Android PopupMenu set gravity as CENTER does not work

iori24 picture iori24 · Nov 9, 2017 · Viewed 8.5k times · Source

I tried this code. and also tried CENTER_HORIZONTAL and CENTER_VERTICAL. Still the anchor is at the left side of the view

val menu = PopupMenu(this, view, Gravity.CENTER)
menu.inflate (R.menu.menu_avatar_2)
menu.show()

enter image description here

Answer

Kingfisher Phuoc picture Kingfisher Phuoc · Nov 9, 2017

You cannot control it with default PopupMenu and PopupMenu(this, view, Gravity.CENTER) only set the gravity of PopuMenu to the right of your anchorView.

If you really want to have gravity in text, here're the options for you:

1: Using PopupWindow:

PopupWindow popupWindow = new PopupWindow(MainActivity.this);
popupWindow.setContentView(yourCustomView); // customview with list of textviews (with gravity inside)
popupWindow.showAsDropDown(anchorView); // display below the anchorview

2: using ListPopupWindow:

String[] products = {"Camera", "Laptop", "Watch", "Smartphone",
                        "Television", "Car", "Motor", "Shoes", "Clothes"};
ListPopupWindow listPopupWindow = new ListPopupWindow(MainActivity.this);
listPopupWindow.setAnchorView(view);
listPopupWindow.setDropDownGravity(Gravity.RIGHT);
listPopupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
listPopupWindow.setWidth(300);
listPopupWindow.setAdapter(new ArrayAdapter(MainActivity.this,
                            R.layout.list_item, products)); // list_item is your textView with gravity.
listPopupWindow.show();