Search code examples
androidandroid-menuandroid-11

androidx.appcompat.app.AppCompatActivity#closeOptionsMenu doesn't close the menu


I'm using a click on the menu to open a bottom sheet.

When this was initially implemented just returning false from AppCompatActivity#onMenuOpened didn't do the job.

I see that someone already complained about this 5 years ago.

So I added a call to AppCompatActivity#closeOptionsMenu and it worked.

I updated my app to support API level 30 and now I noticed that it doesn't work. (Not sure if this is related to API 30, or if it broke earlier and I didn't notice)

This is the current code of AppCompatActivity#closeOptionsMenu

        ActionBar actionBar = getSupportActionBar();
        if (getWindow().hasFeature(Window.FEATURE_OPTIONS_PANEL)
                && (actionBar == null || !actionBar.closeOptionsMenu())) {
            super.closeOptionsMenu();
        }

and the result of actionBar.closeOptionsMenu() is true - i.e. super.closeOptionsMenu() isn't called. So I thought I would call the code in android.app.Activity#closeOptionsMenu directly

    public void closeOptionsMenu() {
        if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
                (mActionBar == null || !mActionBar.closeOptionsMenu())) {
            mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
        }
    }

but this call mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL); still didn't change things and the menu is still opened.

Any idea on how to fix this?


Solution

  • Instead of calling closeOptionsMenu inside onMenuOpened - I posted the close method to be called after onMenuOpened.

        public boolean onMenuOpened(int featureId, Menu menu) {
            // Make sure the menu won't open
            new Handler().post(this::closeOptionsMenu);
    
            openBottomSheetMenu();
            return false;
        }
    

    And this solved the specific issue I had - I still see the menu for a sec, but then it's closed. I assume that it's wrong to call close while open is still running.

    Still no sure why returning false didn't work