i have an activity with bottom navigation view with 3 Fragments associated. One of them is a Fragment with a ViewPager2 that uses a FragmentStateAdapter. Inside the createfragment(int position) method of the Adapter I return a couple Instances of another Fragment which has an Options Menu and inside it's onCreate() i call setHasOptionsMenu(true). The Problem is that on initialization of the adapter, the menu from all fragments are visible not just the menu of the currently visible fragment. After the first swipe it seems that the menu gets invalidated and everything is as it should be. The problem also occurs if i notify the adapter about changes that another fragment is added, then another menu item appears for the newly added fragment. I saw a similar question but the answer was to call setHasOptionsMenu() inside the onResume() method of the fragment but that doesn't seem to be the right behavior to handle this. In a comment another user suggested to upgrade ViewPager2 to another version but I am using the latest version. Can anybody tell me how to handle this?
I joined StackOverflow just to reply to this question as I've also wasted time on this exact issue.
The fix is to update to the latest alpha01 version of ViewPager2.
implementation "androidx.viewpager2:viewpager2:1.1.0-alpha01"
See: https://developer.android.com/jetpack/androidx/releases/viewpager2#1.1.0-alpha01
Fixed FragmentStateAdapter issue with initial fragment menu visibility when adding a fragment to the FragmentManager. (I9d2ff, b/144442240)