问题
Is it possible to enable-disable swiping in new android viewpager2 component?
回答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-alpha02
New features
- Ability to disable user input (
setUserInputEnabled,isUserInputEnabled)
API changes
ViewPager2class final
Bug fixes
FragmentStateAdapterstability fixes
SAMPLE CODE to disable swiping in viewpager2
myViewPager2.setUserInputEnabled(false);
SAMPLE CODE to enable swiping in viewpager2
myViewPager2.setUserInputEnabled(true);
回答2:
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.
来源:https://stackoverflow.com/questions/54978846/how-to-disable-swiping-in-viewpager2