How can I change option menu in different fragments?

alfo888_ibg picture alfo888_ibg · Apr 28, 2014 · Viewed 18.4k times · Source

I have a Fragment with menu:

public class FragmentA extends Fragment {

    public FragmentA() {
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        setHasOptionsMenu(true);
    }

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

I would like to change menu but it doesn't work and keep the old action menu

Fragment B is equals like above with different inflate XML menu.

public class FragmentB extends Fragment {

    public FragmentB() {
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        setHasOptionsMenu(true);
    }

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

EDITED:

Can be useful to use different menu layout for different fragments and 1 menu layout for main activity and differents id

Answer

Boban S. picture Boban S. · Apr 28, 2014

Put setHasOptionsMenu(true) in constructor and inflate fragment specific menu.

public class FragmentA extends Fragment {

    public FragmentA() {
       setHasOptionsMenu(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        setHasOptionsMenu(true);
    }

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

menu in main activity

public class MainActivity extends Activity {
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
}