答案 0 :(得分:2)
您无法使用默认PopupMenu
和\ n来控制它
PopupMenu(this, view, Gravity.CENTER)
仅将PopuMenu
的严重性设置在anchorView
的右侧。
如果您真的希望在文本中使用重力,请在此处为您选择:
1:使用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:使用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();
答案 1 :(得分:1)
很难完全将PopupMenu或PopupWindow对齐到锚点,因为它的位置部分取决于文本标签的长度。但是您可以更改水平和垂直偏移,使其更加集中:
styles.xml:
<style name="PopupMenuMoreCentralized" parent="@style/Widget.AppCompat.PopupMenu">
<item name="android:dropDownHorizontalOffset">4dp</item>
<item name="android:dropDownVerticalOffset">-6dp</item>
</style>
Java代码:
new PopupMenu(context, anchor, Gravity.CENTER, 0, R.style.PopupMenuMoreCentralized)
或
MenuPopupHelper menuPopupHelper = new MenuPopupHelper(context,
(MenuBuilder) popupMenu.getMenu(),
anchor,
false,
0,
R.style.PopupMenuMoreCentralized);