Android PopupMenu将重力设置为CENTER不起作用

时间:2017-11-09 03:47:13

标签: android popupmenu

我试过这段代码。 并尝试过CENTER_HORIZONTAL和CENTER_VERTICAL。 锚点仍位于视图的左侧

item.day

enter image description here

2 个答案:

答案 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);

来源:Implement pop up Menu with margin