How to programmatically check if the menu of my activity is displayed at a certain moment?

Changing the configuration of an Android device (for example, β€œslide the hard keyboard back”) will always call PhoneWindow.onConfigurationChanged() , which in turn will call reopenMenu() . This will re-open the menu of the current activity, if it is displayed.

I have a lock in my menu implemented in my onPrepareOptionsMenu() override. The user must enter the code every time he wants to see the menu. I do not want the user to be asked to enter the code again, and the menu is still only due to a configuration change. So, I would like to know if there is a way to check if the menu of the current foreground activity is displayed? Knowing this, I can bypass the access code request if the menu has already been completed.

My custom temporary implementation is to use my own menuShowing flag, which I set to onPrepareOptionsMenu and reset to onOptionsItemSelected and onKeyDown if the back button is pressed.

EDIT: It seems that changing the screen orientation configuration does not cause this behavior. However, a hard keyboard slide does.

+6
source share
2 answers

While someone comes up with a more pleasant one-call answer, here is the usual temporary implementation, which I mention in the question, using Sam's advice if someone needs the same functionality:

 @Override public boolean onPrepareOptionsMenu(Menu menu) { if (showingMenu) { // The menu button was clicked or the hard keyboard was // slid open/closed while the menu was already showing return true; } // Otherwise, either the menu was clicked or openOptionsMenu() was called if (codeEntered) { // Code was entered and then openOptionsMenu() was called showingMenu = true; // Menu will now be shown return true; } else { // The menu button was clicked, ask for code askForCode(); // Don't show menu yet return false; } } @Override public void onOptionsMenuClosed(Menu menu) { showingMenu = false; codeEntered = false; } private void askForCode() { codeEntered = getUserInput(); if (codeEntered) openOptionsMenu(); } 

getUserInput() actually happens using AlertDialog and EditText with a TextWatcher attached, but implementation details exceed the scope of this question, unless someone is interested.

+2
source

In my case it is

  @Override public void onPanelClosed(int featureId, Menu menu) { showingMenu = false; super.onPanelClosed(featureId, menu); } 
0
source

Source: https://habr.com/ru/post/915447/


All Articles