Reputation: 45
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?
Upvotes: 3
Views: 3023
Reputation: 11
I solved it like this:
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition()==0||tab.getPosition()==1||tab.getPosition()==2||tab.getPosition()==3){
pagerAdapter.notifyDataSetChanged();
}
Upvotes: 0
Reputation: 2335
I had a similar problem, if not the same. The solution was to change fragments
/tabs
/pages
in a specific order.
FragmentStateAdapter
should be notified first of the change to the fragment.TabLayout
should then call selectTab
under a post
ViewPager
should then call setCurrentItem
under a post
, inside the TabLayouts post
to selectTab
.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();
});
});
Upvotes: 6