Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android PopupMenu set gravity as CENTER does not work

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

like image 522
iori24 Avatar asked Nov 09 '17 03:11

iori24


2 Answers

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();
like image 119
Kingfisher Phuoc Avatar answered Oct 22 '22 00:10

Kingfisher Phuoc


It's difficult to perfectly center-align a PopupMenu or PopupWindow to the anchor, because its position is partially determined by the length of the text labels. But you can change the horizontal and vertical offsets to make it a bit more centralized:

styles.xml:

<style name="PopupMenuMoreCentralized" parent="@style/Widget.AppCompat.PopupMenu">
    <item name="android:dropDownHorizontalOffset">4dp</item>
    <item name="android:dropDownVerticalOffset">-6dp</item>
</style>

Java code:

new PopupMenu(context, anchor, Gravity.CENTER, 0, R.style.PopupMenuMoreCentralized)

or

MenuPopupHelper menuPopupHelper = new MenuPopupHelper(context,
        (MenuBuilder) popupMenu.getMenu(),
        anchor,
        false,
        0,
        R.style.PopupMenuMoreCentralized);

Source: Implement pop up Menu with margin

like image 25
Mr-IDE Avatar answered Oct 22 '22 00:10

Mr-IDE