Manfred Moser
Manfred Moser

Reputation: 29912

Hide action bar menu items from invisible fragment

I use 3 FrameLayouts in my activity view xml into which I dynamically insert different fragments. Many of these fragments contribute ActionBar MenuItems. Now I have a situation where I hide a FrameLayout (set visibility to View.GONE) and therefore the Fragment in it becomes invisible. However it still contributes the menu item since the fragment does not to seem to be paused or anything so I cant seem to call a method that actively hides the action bar item.

As a solution I now just insert a fragment into the FrameLayout that has no menu item when I switch the FrameLayout to invisible. While that works it feels like a hack to me. What is the proper way to hide any action bar menu items? What states does the fragment go into if I just hide the layout it is in?

I am doing all this with the compatibility library r6 in case that matters.

Upvotes: 2

Views: 2905

Answers (2)

Paweł Krakowiak
Paweł Krakowiak

Reputation: 368

I had a similar problem - an Activity with two FrameLayouts:

  • on the horizontal screen rotation both were visible,
  • on the vertical screen rotation only one was visible.

    Both contained Fragments with some menu items. After switching from the horizontal to the vertical view menu items from both Fragments were visible. I have resolved it by using a popBackStack() functionality in the onCreate() method like in the code below:

    getSupportFragmentManager().popBackStack();
    
    FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
    tr.replace(getListContainer(), listFragment);
    if (detailPanelVisible) {
        Fragment detailFragment = createDetailFragment();
        tr.replace(getDetailContainer(), detailFragment);
    }
    tr.addToBackStack(null);
    tr.commit();
    

    Maybe this can do the work for you.

    Upvotes: 1

  • Neal Sanche
    Neal Sanche

    Reputation: 1626

    You should be able to call invalidateOptionsMenu() in your FragmentActivity derived activity which will cause all of the fragments onCreateOptionsMenu() methods to be called again, and you can hide any menu items you don't want visible any more.

    Upvotes: 1

    Related Questions