13

I have viewpager2 and adapter for him that extends FragmentStateAdapter. I want user to go to another page only by clicking on tablayout. I have disabled user input for this viewpager2. But when I click on tab, there is animation of fast swiping between pages. But I want just new fragment to show. Like with FragmentTransaction, but with viewpager2 and tablayout. Does anyone knows ho to do it?

DenBondd
  • 155
  • 1
  • 1
  • 9
  • weird. my viewpager2 animation is so slow. i want it to go faster. didnt set anything else just the default smooth scrolling. problem is, its too smooth that its slow. – chitgoks Oct 20 '21 at 14:05

3 Answers3

18

You should use addOnTabSelectedListener like this:

    tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabReselected(tab: TabLayout.Tab?) {
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
        }

        override fun onTabSelected(tab: TabLayout.Tab?) {
            tab?.position?.let { viewPager?.setCurrentItem(it, false) }
        }

    })

You already use

viewPager.isUserInputEnabled = false

Note : setCurrentItem(int item, boolean smoothScroll)

Set the currently selected page with smooth scroll. If you set smooth scroll is false, you don't see the animation

Kasım Özdemir
  • 5,414
  • 3
  • 18
  • 35
14

TabLayoutMediator is what you need. Just set smoothScroll to false.

public TabLayoutMediator(
  @NonNull TabLayout tabLayout,
  @NonNull ViewPager2 viewPager,
  boolean autoRefresh,
  boolean smoothScroll,
  @NonNull TabConfigurationStrategy tabConfigurationStrategy) 

https://developer.android.com/reference/com/google/android/material/tabs/TabLayoutMediator

Ocor Kcirad
  • 354
  • 2
  • 4
1

I think viewpager2.setPageTransformer(null) might give you what you need

https://developer.android.com/reference/kotlin/androidx/viewpager2/widget/ViewPager2#setpagetransformer

Note: setting a PageTransformer disables data-set change animations to prevent conflicts between the two animation systems. Setting a null transformer will restore data-set change animations.

Andrew
  • 8,198
  • 2
  • 15
  • 35