14

I want to listen when user opens/closes the overflow menu (three dots) of ActionBar, someway like this:

void onOverflowMenu(boolean expanded) {
}

To handle open cases, I've tried onPrepareOptionsMenu(), but it's triggered when ActionBar is constructed or when invalidateOptionsMenu() is called. This is not what I want.

I was able to detect overflow menu is closed if user selects a menu item in onMenuItemSelected(). But I also want to detect it if user closes overflow menu by tapping outside of it, by pressing back key, and all other cases.

Is there a way to implement that?

Leo K
  • 808
  • 1
  • 9
  • 24
Dima Kornilov
  • 2,003
  • 3
  • 16
  • 25
  • Try checking if `onMenuItemSelected()` when you press on your overflow menu. If it is triggered you could debug your application and check what you need to do in order to proper catch that event. – zozelfelfo May 22 '14 at 12:12

2 Answers2

22

To catch open action in the Activity:

@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    ...
    return super.onMenuOpened(featureId, menu);
}

To catch closed action, also if user touch outside of Menu view:

@Override
public void onPanelClosed(int featureId, Menu menu) {
    ...
}
Community
  • 1
  • 1
schabluk
  • 708
  • 8
  • 17
  • 4
    Thanks! It works. Also I added check if (featureId == FEATURE_ACTION_BAR) to make sure which menu has been triggered. – Dima Kornilov May 22 '14 at 12:35
  • 1
    onMenuOpened is fired twice which is not accurate if you are trying to track analytics on the Overflow menu being opened. – AdamHurwitz Apr 13 '17 at 23:52
  • 2
    Please refer to the correct solution here. http://stackoverflow.com/questions/41558904/why-is-menu-of-appcompatactivity-onmenuopenedint-featureid-menu-menu-null onPrepareOptionsMenu() will be called only once when the overflow menu is opened. – AdamHurwitz Apr 14 '17 at 00:03
  • How can we check similar scenario with overflow menu inside a fragment? – Roohi Zuwairiyah Mar 29 '19 at 14:23
6

IMHO the simplest way is to set ActionBar.OnMenuVisibilityListener

ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
    actionBar.addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
        @Override
        public void onMenuVisibilityChanged(boolean isVisible) {
            if (isVisible) {
                // menu expanded
            } else {
                // menu collapsed
            }
        }
    });
}
pratt
  • 1,534
  • 14
  • 17