Popup menu comes out in left bottom

爱⌒轻易说出口 提交于 2021-02-11 13:10:49

问题


I am trying to implement popup menu in my fragment but the result is far beyond my desire. I have a button on the action bar and one of these buttons call the popup menu and no problem till here. It successfully calls and I can see the popup menu. Here is how I do that.

In fragment class

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.x) {           
    } else showPopup(view /* or getView() */);

    return super.onOptionsItemSelected(item);
}

public void showPopup(View v) {
    PopupMenu popupMenu = new PopupMenu(getContext(), v);
    MenuInflater menuInflater = popupMenu.getMenuInflater();
    menuInflater.inflate(R.menu.event_popup, popupMenu.getMenu());
    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            return false;
        }
    });
    popupMenu.show();
}

popup_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/a"
    android:icon="@drawable/ic_action_back"
    android:title="a" />

<item android:id="@+id/b"
    android:icon="@drawable/ic_action_back"
    android:title="b" />

Fragment's action menu (includes button which opens popup menu)

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/x"
    android:icon="@drawable/ic_action_back"
    yourapp:showAsAction="ifRoom"
    android:title="" />

<item android:id="@+id/y"
    android:icon="@drawable/ic_action_menu_dot"
    yourapp:showAsAction="ifRoom"
    android:title="" />

</menu>

And in the result here is how it looks. I want it to be on top right. How can I handle this. As far as I know, Its default placement is already top right.


回答1:


You need to provide proper anchor view (overflow menu in this case) to the popup menu.

Try changing

showPopup(view);

to

View menuItemView = MyActivity.this.findViewById(R.id.overflow_menu); // replace with your id
showPopup(menuItemView);

This should bring the popup menu to top. If its still on the left side use

popupMenu.setGravity(Gravity.END);


来源:https://stackoverflow.com/questions/53337344/popup-menu-comes-out-in-left-bottom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!