How to disable swiping in ViewPager2?

AndroidAndroidxAndroid Viewpager2

Android Problem Overview


Is it possible to enable-disable swiping in new android viewpager2 component?

Android Solutions


Solution 1 - Android

Now it is possible to enable-disable swiping viewpager2 using Version 1.0.0-alpha02

Use implementation 'androidx.viewpager2:viewpager2:1.0.0-alpha02'

>Version 1.0.0

New features

  • Ability to disable user input (setUserInputEnabled, isUserInputEnabled)

API changes

  • ViewPager2 class final

Bug fixes

  • FragmentStateAdapter stability fixes

SAMPLE CODE to disable swiping in viewpager2

myViewPager2.setUserInputEnabled(false);

SAMPLE CODE to enable swiping in viewpager2

myViewPager2.setUserInputEnabled(true);

Solution 2 - Android

If you are using Android Data Binding you can simply disable it your layout xml file.

app:userInputEnabled="@{false}"

Solution 3 - Android

viewPager2.setUserInputEnabled(false);

Solution 4 - Android

Under the hood ViewPager2 works with RecyclerView for inflating the fragment views, but the RecyclerView is hidden so they make it more idiot proof.

 val rv : RecyclerView = viewPager.getChildAt(0) as RecyclerView
 rv.layoutManager = NonScrollingLayoutManager( rv.context, rv.layoutManager as LinearLayoutManager)
    

Hacky way is to get the child at position zero which is the RecyclerView and disable scrolling in the layout manager, by wrapping the layout manager:

inner class NonScrollingLayoutManager(context: Context, val layoutManager: LinearLayoutManager) :
    LinearLayoutManager(context, layoutManager.orientation, layoutManager.reverseLayout) {

    override fun canScrollVertically(): Boolean  = layoutManager.orientation == HORIZONTAL


    override fun canScrollHorizontally(): Boolean  =  layoutManager.orientation == VERTICAL

}

Please beware that if the API changes the layout manager used for the RecyclerView, i.e they move away from the LinearLayoutManager this wont work and it will need some methods overriden and ensure super methods are called.

Second approach is subclass the ViewPager2 which is ViewGroup and then do the magic in intercepting touch events, before they are dispatched to the child views (as you would guess the RecyclerView) and be careful not to prevent clicks.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmurgupluogluView Question on Stackoverflow
Solution 1 - AndroidAskNileshView Answer on Stackoverflow
Solution 2 - AndroidDennisView Answer on Stackoverflow
Solution 3 - AndroidYaminiView Answer on Stackoverflow
Solution 4 - AndroidNikola DespotoskiView Answer on Stackoverflow