In my Android app I want to collect statistics on when (how often) the overflow (three dots) action bar menu is opened and closed (without an item being selected). For this task I have overriden onMenuOpened
and onPanelClosed
methods within an Activity
. However, on all the devices (Android 4.4, 4.2; Samsung and HTC) I've tried this so far these methods are triggered twice, each time the menu is opened and closed.
Is this a bug? Is there another way to monitor this menu opening and closing?
Asked
Active
Viewed 1,550 times
7

Leo K
- 808
- 1
- 9
- 24
3 Answers
8
you can try this...i have tested it ....it works perfect....
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Activity activity = getActivity();
activity.getActionBar().addOnMenuVisibilityListener(new OnMenuVisibilityListener() {
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
// TODO Auto-generated method stub
//you can check the isVisible boolean to check
// if the overFlowMenu is visible or not
}
});

the_D
- 890
- 13
- 26
-
Please try to improve the writing of your answer. Also, commenting the code would help. – fedorqui Aug 04 '14 at 11:17
-
I'm going to accept your answer. However, I'd like to add that I did try this approach previously, and it also resulted in the same bug as I described in the question. However, I was setting the listener in onCreateOptionsMenu, setting the listener inside onCreated instead solved this. In conclusion this approach does work. Also, I'm not really sure why you suggested using isOverflowMenuOpen field, it's not really necessary the isVisible parameter provides the same information. – Leo K Aug 04 '14 at 21:39
4
I got the same question as you, and find an easier way to solve it:
When the first time it enters onMenuOpened(), menu is null. The menu is not prepared yet. So, you can check as below
@Override
public boolean onMenuOpened(int featureId, Menu menu){
if(menu!=null){
//log something like firebaseLogEvent("Action", "onMenuOpened");
}
return true;
}

Fisher
- 488
- 7
- 24
0
Discovered a better solution
public boolean onPrepareOptionsMenu(Menu menu) {
if (hasWindowFocus ()) {
// gets called every time user taps on menu
Log.v(TAG, "onPrepareOptionsMenu - focus");
} else {
// gets called when menu is being initialized
Log.v(TAG, "onPrepareOptionsMenu - NO FOCUS");
}
return super.onPrepareOptionsMenu(menu);
}
You can collect you stats in the "focus" part of the If statement.

Sarang
- 2,143
- 24
- 21