Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with OptionsMenu in nested fragment

I use a NavigationDrawer pattern that is implemented in my hostactivity MenuActivity. My navigation has 3 items: Item 1, Item 2, Item 3. Each itemis bonded to a fragment.

When I click on Item 1, I displayed a fragment A that implements a ViewPager with several fragments (nested fragments).

In my nested fragments, I inflate a menu with the following method (It works fine !) :

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.my_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

But when I click on another element of my menu (Item 2 -> display Fragment B or Item 3->display Fragment C), my menu (which was inflated in my nested fragment) is always visible but I want it to disappear.

Would you have a solution to this problem? Thank you in advance.

like image 750
frenchdev20 Avatar asked Sep 28 '22 01:09

frenchdev20


3 Answers

Just save child fragment and then override setMenuVisability:

@Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (savedFragment!= null)
            savedFragment.setMenuVisibility(menuVisible);
    }

it works for me

like image 127
Andrei Tr. Avatar answered Oct 16 '22 13:10

Andrei Tr.


When I encountered this problem, I solved it by setting setHasOptionMenu(true) for both the child fragment and the "root" fragment. If the "root" fragment or another child fragment doesn't use option items, it's fine anyway, since you only inflate a menu in the child fragment needing it.

like image 32
Joakim Avatar answered Oct 16 '22 12:10

Joakim


I just came across the problem and solved it by the following:

@Override
public void onDestroyOptionsMenu() {
    this.setMenuVisibility(false);
    super.onDestroyOptionsMenu();
    Log.e(TAG, "onDestroyOptionsMenu");
}

@Override
public void onDestroyView() {
    onDestroyOptionsMenu();
    super.onDestroyView();
}

I noticed that onDestroyOptionsMenu is not being called so what I only did is call it from the OnDestroyView method and I set the menu visibility to false.

like image 1
msamhoury Avatar answered Oct 16 '22 13:10

msamhoury