I have viewPager with several views. the default behavior of viewPager is that the first item is displayed first, then swiping right to left displays the second view right to the current view etc.
the behavior i want is that after the first item is displayed, swiping left to right will display the next view left to the current item.
i searched a lot for clever way to implement this but no results..
thanks in advance.
ViewPager2 uses FragmentStateAdapter objects as a supply for new pages to display, so the FragmentStateAdapter will use the fragment class that you created earlier. Create an activity that does the following things: Sets the content view to be the layout with the ViewPager2 .
To enable / disable the swiping, just overide two methods: onTouchEvent and onInterceptTouchEvent . Both will return "false" if the paging was disabled. You just need to call the setPagingEnabled method with false and users won't be able to swipe to paginate.
Android ViewPager is an interface component introduced in Android support library. It allows the user to swipe left or right to view a completely new page (screen). A ViewPager/ViewPager2 where each page fills the screen, which the user will swipe left to move to the next page, or swipe right to go back one page.
why don't you reverse the list of you view in view pager and use setCurrentItem(int) or setCurrentItem(int,boolean) and set the last one at the launch of the activity/fragment..
You can simply use setCurrentItem()
to navigate to the last page in the ViewPager when it's attached to the View.
I was looking for a way to reverse viewpager2 and came up with this one. It's a dirty hack, but it works
The idea is to mirror the viewpager horizontally, and then mirror each page back
var ViewPager2.isReversedDirection: Boolean
get() = scaleX == -1f
set(value) {
if (value) {
scaleX = -1f // mirror viewpager
val listener = object : RecyclerView.OnChildAttachStateChangeListener {
override fun onChildViewDetachedFromWindow(view: View) = Unit
override fun onChildViewAttachedToWindow(view: View) {
view.scaleX = -1f // mirror the page back when it was attached
}
}
val recyclerView = getChildAt(0) as RecyclerView
recyclerView.addOnChildAttachStateChangeListener(listener)
}
}
Since it depends on the internal implementation of viewpager, it tested on androidx.viewpager2:viewpager2:1.0.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With