Search code examples
androidandroid-toolbarpopupmenuoptionmenu

MenuPopupHelper cannot be used without an anchor


I want add PopupMenu to my MenuItem.

Menu.xml

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

    <item
        android:id="@+id/date"
        app:showAsAction="ifRoom|withText"
        android:title="Date"
        android:visible="true"/>
    <item
        android:id="@+id/category"
        app:showAsAction="ifRoom|withText"
        android:title="Category"
        android:visible="true"/>
</menu>

When I click on MenuItem I call this code:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.filter_action) {
        showPopup(item.getActionView());
    }
    return super.onOptionsItemSelected(item);
}

private void showPopup(View v) {
    PopupMenu popup = new PopupMenu(getActivity(), v);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.filter_billing_menu, popup.getMenu());
    popup.show();
}

And I get this exception:

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

How I can fix it?


Solution

  • I'm reading "internet" and I try this code:

    showPopu(getActivity().findViewById(R.id.filter_action));
    

    Instead

    showPopup(item.getActionView());
    

    It's works for me