I have been trying to implement two directional Endless viewpager in Android, Left to Right & Right to Left
I have implemented Endless viewpager adapter, it works fine for right to left direction, I have set current item position by viewPager.setCurrentItem(Integer.MAX_VALUE/2);
.
Help would be appreciate.
Step 1: Create a new project and name it AndroidViewPagerExample. Step 2: Download three images Apple,Orange and Grapes from the web. Now save those images in the drawable folder of your project. Step 3: Now open res -> layout -> activity_main.xml and add following code: Add a new xml file inside/res/layoutfolder, with name activity_main.xml.
You can create swipe views using AndroidX's ViewPager2 widget. To use ViewPager2 and tabs, you need to add a dependency on ViewPager2 and on Material Components to your project. To set up your layout with ViewPager2, add the <ViewPager2> element to your XML layout.
The most important feature of viewpager2 that is not present in Viewpager is, the Recyclerview which makes Viewpager2 more efficient than Viewpager. By using the Recyclerview, we can add items dynamically.
By default the orientation of viewpager2 is Horizontal. We can set the orientation of viewpager2 to Vertical by calling the setOrientation () method and passing ORIENTATION_VERTICAL to it. For Horizontal Orientation use To use ViewPager2, you have to first add the dependency in your Build.gradle file:
One simple way to achieve this for ViewPager2
is with 3 basic ideas:
listOf(1, 2, 3, 4, 5)
should become listOf(5, 1, 2, 3, 4, 5, 1)
.Some sample code to do this is as follows:
1.
private fun <T> List<T>.prepareForTwoWayPaging(): List<T> {
val first = first()
val last = last()
return toMutableList().apply {
add(0, last)
add(first)
}
}
pager.setCurrentItem(1, false)
pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
// We're only interested when the pager offset is exactly centered. This
// will help create a convincing illusion of two-way paging.
if (positionOffsetPixels != 0) {
return
}
when (position) {
0 -> pager.setCurrentItem(adapter.itemCount - 2, false)
adapter.itemCount - 1 -> pager.setCurrentItem(1, false)
}
}
})
Caveat: this code does not reconcile any TabLayout
or an empty data model collection.
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