0
votes

Since I can't prevent default action bar menu from closing after selecting an item, I thought of using a popupmenu instead. I want to use my popup menu with the same layout of the android action bar menu, so here's my menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" xmlns:app="http://schemas.android.com/apk/res-auto">

<group android:id="@+id/grp_filtro_selezione" android:checkableBehavior="all">
    <item android:id="@+id/menu_all"
        android:src="@drawable/ic_settings"
        android:title="@string/all_menu"
        android:checked="true"/>
    <item android:id="@+id/menu_aule"
        android:src="@drawable/ic_settings"
        android:title="@string/aule_menu"
        android:checked="false"/>
    <item android:id="@+id/menu_aule_studio"
        android:src="@drawable/ic_settings"
        android:title="@string/aule_studio_menu"
        android:checked="false"/>
</group>
</menu>

I can't figure out how I can use my popup menu with something like this:

 PopupMenu popup = new PopupMenu(MainActivity.this, v);
 popup.getMenuInflater().inflate(R.menu.pop_up, popup.getMenu());

and disabling the default action bar menu.

I think I should use the onCreateOptionsMenu()

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.mymenu, menu);

}

but how can I inflate my popup menu?

EDIT:

I almost found the solution but I have one problem. So, what i did is in the onCreateOptionsMenu I inflated a menu that includes only the action bar icons:

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.prova_menu, menu);
}

And in the onOptionsItemSelected I tried this:

switch (item.getItemId()) {
        case R.id.settings:
            View menuItemView = getActivity().findViewById(R.id.settings); 
            popupMenu = new PopupMenu(getActivity(), menuItemView);
            popupMenu.inflate(R.menu.prova2);
            popupMenu.show();
}

It works fine, but there is a problem. The popup menu that I am showing has selectable items. When I click the icon to open the menu again all the items get reset probably because I inflate the menu layout everytime I show the popup menu. I tried inflating the popup menu only one time in the onCreateOptionsMenu but I get this error when I call popupMenu.show().

 MenuPopupHelper cannot be used without an anchor
2

2 Answers

0
votes

I think you most likely use onCreateOptionsMenu instead of onCreateContextMenu.

Have a look at the API description or the Training Guide on Menus

0
votes

Are you missing call to popup.show()?