[英]Android PopupMenu set gravity as CENTER does not work
你不能用默认的控制它PopupMenu
和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();
很难将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);
来源: 实施带有边距的弹出菜单
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.