Serkay Sarıman
Serkay Sarıman

Reputation: 475

Change actionbar menu in fragment

I want to load another menu xml when I load the fragment.I am using this code in main activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

I am using this code in fragment:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
    getActivity().getMenuInflater().inflate(R.menu.fragment_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

When user loads the fragment,activity menu should remove then fragment menu should load to actionbar. And when user clicks the back button from fragment,fragment menu should remove then main activity menu should load to action bar.

Now this code is not removing the old menu,it's adding new menu to near of old menu.

How can I do this ?

Upvotes: 4

Views: 2968

Answers (3)

Mehran Mahmoudkhani
Mehran Mahmoudkhani

Reputation: 456

You Should call setHasOptionsMenu(true); method in onCreateView.

It tells fragment got a menu.

Then Try below codes...

@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.fragment_manage, container, false);
    }


@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
    menu.clear(); // clears all menu items..
    inflater.inflate(R.menu.fragment_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Upvotes: 3

Pragnesh Ghoda  シ
Pragnesh Ghoda シ

Reputation: 8337

You Can use menu.clear(); method.

It remove all existing items from the menu, leaving it empty as if it had just been created.

Try this..

@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
    menu.clear(); // clears all menu items..
    getActivity().getMenuInflater().inflate(R.menu.fragment_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Upvotes: 9

zozelfelfo
zozelfelfo

Reputation: 3776

Try this:

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

Hope it helps

Upvotes: 2

Related Questions