How to disable swiping in ViewPager2?
Is it possible to enable-disable swiping in new android viewpager2
component?
Solution 1:
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:
If you are using Android Data Binding you can simply disable it your layout xml file.
app:userInputEnabled="@{false}"
Solution 3:
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.
Solution 4:
viewPager2.setUserInputEnabled(false);