Show popup menu on `ActionBar` item click

So finally I found solution. When you want to anchor popupmenu to ActionItem in ActionBar you need to find view that renders ActionItem. Simple find view with findViewById() where id is same as id of your menu item in xml.

DISPLAYING POPUP:

public boolean onOptionsItemSelected(MenuItem item) {
    // ...

    View menuItemView = findViewById(R.id.menu_overflow); // SAME ID AS MENU ID
    PopupMenu popupMenu = new PopupMenu(this, menuItemView); 
    popupMenu.inflate(R.menu.counters_overflow);
    // ...
    popupMenu.show();
    // ...
    return true;
}

MENU:

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

     ....

     <item
    android:id="@+id/menu_overflow"
    android:icon="@drawable/ic_overflow"
    android:showAsAction="ifRoom"
    android:title="@string/menu_overflow"/>

     ....

</menu>

If menu item is not visible (is in overflow) it does not work. findViewById returns null so you have to check for this situation and anchor to another view.


The accepted answer wasn't working for me, so I found the problem by trial and error.

public boolean onOptionsItemSelected(MenuItem item) 
{
    View menuItemView = findViewById(item.getItemId()); 
    showPopupMenu(menuItemView)

    return true;
}

private void showPopupMenu(View anchor)
{
    PopupMenu popup = new PopupMenu(this, anchor);
    popup.getMenuInflater().inflate(R.menu.my_popup_menu, popup.getMenu());
    popup.show();
}

The key here is that, the item in onOptionsItemSelected(MenuItem item) must be shown on ActionBar. If the item is one of the items that appear when you press the 3 vertical dots on top right of ActionBar, then your app will crash.

enter image description here