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

ior*_*i24 5 android popupmenu

我试过这个代码。并且还尝试了 CENTER_HORIZONTAL 和 CENTER_VERTICAL。锚仍然在视图的左侧

val menu = PopupMenu(this, view, Gravity.CENTER)
menu.inflate (R.menu.menu_avatar_2)
menu.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Kin*_*uoc 6

你不能用默认的控制它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
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)