OptionsMenu of Fragments in Viewpager showing each other's Buttons OptionsMenu of Fragments in Viewpager showing each other's Buttons android android

OptionsMenu of Fragments in Viewpager showing each other's Buttons


In your ViewPager's OnPageChangeListener and after setting the adapter to the ViewPager, have this:

@Overridepublic void onPageSelected(int position){   invalidateFragmentMenus(position);}private void invalidateFragmentMenus(int position){   for(int i = 0; i < mViewPagerFragentAdapter.getCount(); i++){      mViewPagerAdapter.getItem(i).setHasOptionsMenu(i == position);   }   invalidateOptionsMenu(); //or respectively its support method.}

After setting your fragment adapter call the same method with following argument:

invalidateFragmentMenus(mViewPager.getCurrentItem());

The above statements will prevent all other fragments not to receive call on onCreateOptionsMenu() method when invalidateOptionsMenu() is called, only the currently visible fragment will receive and be able to populate the options menu.


I've used this and it has worked for me:

//In your Fragment@Overridepublic void onResume() {    super.onResume();    setHasOptionsMenu(isVisible());}