Cocorico
Cocorico

Reputation: 2018

Different menu for different Fragment Tabs

Description: 1) I have an Activity which contains one fragment. I replace sometimes this fragment with a menu. (First Level) 2) One of thus fragments is an tabFragments. It contains one fragments but this fragment can be replace when user click on a tab. (Second level)

I use Android over 4.0.

My question is: How can I have "General" Menu for the RootActivity + a "Normal" Menu for my tabfragment + an other menu for my fragment inside the TabFragment, all in the ActionBar ? In fact, when I switch between fragment in FirstLevel, menu is updated correctly, but when I go to the second level, menu keep item from an other second level Fragment. And when I come back to an other first level Fragments I still have menu from a second level fragment.

Edit :

First Level Fragment (TabFragment)

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_intervention, menu);
        super.onCreateOptionsMenu(menu, inflater);
        // Inflate Menu below;
    }

Second Level Fragment:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    // Inflate Menu below;
    inflater.inflate(R.menu.menu_intervention_inventaire, menu);
}

Upvotes: 0

Views: 538

Answers (1)

LordRaydenMK
LordRaydenMK

Reputation: 13321

It is possible.

In your fragment's onCreate method call setHasOptionsMenu(true). Do the same for your child fragment.

Then override onCreateOptionsMenu and onOptionsItemSelected.

Don't forget to call super.onCreateOptionsMenu from your fragments.

Put the common menu items in the Activity. And the other items in the appropriate fragment fragment.

Edit: You should use ChildFragmentManager for your child fragments. It's available in the support library.

Upvotes: 2

Related Questions