Skip to content
Advertisement

How can I change option menu in different fragments?

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

Advertisement

Answer

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);
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement