Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

menu inflating calls multiple times at fragment's onCreateOptionsMenu

I use Fragments and when I switch to nested Fragment, which implements public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) my menu inflates quantity of times when I get to that nested Fragment. How can I avoid this? I also implement constructor of Fragment with methods:

setRetainInstance(true);
setHasOptionsMenu(true);

When I tried to implement siple solution as:

 @Override
 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     // TODO Add your menu entries here
   if(!isInflated)
         {
         inflater.inflate(R.menu.contacts_archive_menu, menu);
         isInflated = true;
         }
         super.onCreateOptionsMenu(menu, inflater);

 }

but my menu wasn't inflate after the screen rotation.

like image 963
Rikki Tikki Tavi Avatar asked Sep 12 '13 15:09

Rikki Tikki Tavi


2 Answers

I solved it simply by clearing menu before ionflating of it:

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

     }
like image 124
Rikki Tikki Tavi Avatar answered Nov 04 '22 06:11

Rikki Tikki Tavi


Just check the count of menu items. Meaning menu.size()==0 ,no menu items are present,then inflate with layout menu,else don't inflate at all.

 @Override
 public void   onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
      if (menu.size() == 0)
      inflater.inflate(R.menu.call_menu, menu);
      super.onCreateOptionsMenu(menu, inflater);

 }
like image 21
laaptu Avatar answered Nov 04 '22 07:11

laaptu