无法创建菜单

时间:2018-04-22 17:38:38

标签: java android menu

我是Android的新手尝试创建一个弹出菜单,但是当我在我的活动中调用createMenu()时,我的应用程序崩溃了,这延伸到AppCompatActivity任何人都可以帮我解决这个问题?

@SuppressLint("RestrictedApi")
    public void createMenu() {
        MenuBuilder menuBuilder = new MenuBuilder(this);
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.menu.popup_menu, menuBuilder);
        MenuPopupHelper optionsMenu = new MenuPopupHelper(this, menuBuilder);
        optionsMenu.setForceShowIcon(true);
          menuBuilder.setCallback(new MenuBuilder.Callback() {
            @Override
            public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.one:
                        return true;
                    default:
                        return false;
                }
            }

            @Override
            public void onMenuModeChange(MenuBuilder menu) {

            }
        });
        optionsMenu.show();
}

在我的XML

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

    <item
        android:id="@+id/one"
        android:icon="@drawable/ic_one"
        android:title="One"
        android:orderInCategory="0"/>
</menu>

调用它

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.option) {
            createMenu();
        }
}

收到错误

java.lang.IllegalStateException: MenuPopupHelper cannot be used without an anchor

1 个答案:

答案 0 :(得分:0)

将其添加到菜单文件android:showAsAction="always"

使用此菜单文件

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

<item
    android:id="@+id/one"
    android:icon="@drawable/ic_one"
    android:title="One"
    android:showAsAction="always"
    android:orderInCategory="0"/>

问题是空操作视图。因此将menuitem显示为动作视图可以解决问题

并使用此代码调用此

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.option) {
        createMenu(item.getActionView());
    }

}

将您的createMenu()更改为

@SuppressLint("RestrictedApi")
public void createMenu(View v) {
PopupMenu popup = new PopupMenu(getActivity(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_menu, popup.getMenu());
popup.show();

}