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:

  • Android material chips
  • Borderless Button on Pre-Lollipop with Support Library
  • Null pointer Exception on .setOnClickListener
  • Image processing library for Android?
  • Warning : Do not hardcode “/data/”; use Context.getFilesDir().getPath() instead
  • Android Action Bar with Search View
  •  @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.

  • List installed sdk package via command line
  • IntelliJ Idea auto create new method
  • On/Off Toggle Button in Preferences & Action Bar - Ice Cream Sandwich Style
  • Securing php api to use in android application
  • Show soft keyboard when Activity starts
  • How to navigate one page to another page in android phonegap?
  • 3 Solutions collect form web for “menu inflating calls multiple times at fragment's onCreateOptionsMenu”

    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);
    
         }
    

    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);
    
     }
    

    Use before replace.

    fragment = new EditMyProfile();
    android.support.v4.app.FragmentTransaction fragmentTransactionEditProfile =
    getSupportFragmentManager().beginTransaction();
    getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    fragmentTransactionEditProfile.replace(R.id.frame, fragment);
    fragmentTransactionEditProfile.commit();

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.