Prat
Prat

Reputation: 142

Menu inflating issue in Multiple fragment hierarchy

enter image description here

Facing issue while inflating different Menu in different fragment.

My application hierarchy is like: BottomNavigationView --> Fragments(4) ---> Tab+ViewPager --> Fragments(3)

Each fragment contains ViewPager and ViewPager contains multiple fragments.

Please see the attached image for more clarity.

Issue: It's keep on adding new menu, or sometimes carry previous screen menu.

I have tried using "menu.clear()", "getActivity().invalidateOptionsMenu();"

Upvotes: 2

Views: 419

Answers (1)

Misha Akopov
Misha Akopov

Reputation: 13027

You have ViewPager, it means that if you go to ith position, fragments that are on position i-1 and i+1 will also be created. So their onCreateOptionsMenu will be called and even if you call menu.clear() it will not work properly.

Solution is to change menu in container Fragment/Activity of ViewPager , in following way. Add ViewPager.OnPageChangeListener listener to ViewPager and in onPageSelected(int position) method change menu yourself:

@Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            int menuResourceId = getMenuResourceByPosition(position); 
            menu.clear();
            inflater.inflate(menuResourceId, menu);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}

create method getMenuResourceByPosition that will give you proper menu resource id by ViewPager's selected position.

Upvotes: 3

Related Questions