Search code examples
androidandroid-viewpager2

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

  • I had a similar problem, if not the same. The solution was to change fragments/tabs/pages in a specific order.

    1. The FragmentStateAdapter should be notified first of the change to the fragment.
    2. The TabLayout should then call selectTab under a post
    3. The 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();
         });
    });