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()
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With