ViewPager2 setCurrentItem bug workaround?
This reported bug is causing me problems; https://issuetracker.google.com/issues/183847283
When combined with FragmentStateAdapter, ViewPager2.setCurrentItem doesn't always work. The TabLayout correctly changes (if you have one), but the ViewPager2 itself doesn't show the correct page.
Has anyone found a workaround?
Solution 1:
I had a similar problem, if not the same. The solution was to change fragments
/tabs
/pages
in a specific order.
- The
FragmentStateAdapter
should be notified first of the change to the fragment. - The
TabLayout
should then callselectTab
under apost
- The
ViewPager
should then callsetCurrentItem
under apost
, inside the TabLayoutspost
toselectTab
.
This may be overkill but it worked for me.
Example
//or some other notify depending on your use case.
fragmentStateAdapter.notifyItemInserted(position);
tabLayout.post(()->{
tabLayout.selectTab(tabLayout.getTabAt(position));
viewPager2.post(()->{
viewPager2.setCurrentItem(position);
//I noticed on older devices like API 19
//the viewPager wouldn't complete transformations
//so we call this.
viewPager2.requestTransform();
});
});