How can we implement infinite scrolling in ViewPager2
As there is no OnPageChangeListener()
in this pager.
But there is setPageTransformer()
Listener which get callback whenever we change page.
So any solution for viewpager2 problem
Note : I'm using recyclerview adapter for viewpager2
For infinite scrolling, you don't have to customise the view pager. The trick in the viewPager adapter. You can return Int.MAX value in getCount override method. The in the instantiateItem override function you can use item_position % item_size to get the actual item position. Code example is given below.
class AdsSliderAdapter(
private val bannerImageList: MutableList<SliderImagesItem>,
private val callback: SliderItemClickListener) :PagerAdapter() {
private var mContext: Context? = null
override fun instantiateItem(container: ViewGroup, position: Int): Any {
mContext = container.context
val view = LayoutInflater.from(container.context)
.inflate(R.layout.item_ad_slider, container, false)
val adImage: AppCompatImageView = view.ivAd
mContext?.let {
GlideApp.with(it).load(bannerImageList[position % bannerImageList.size].imageUrl)
.into(adImage)
}
val viewPager = container as ViewPager
viewPager.addView(view, 0)
view.cardView.onClick { callback.onSliderImageClick(bannerImageList[position % bannerImageList.size]) }
return view
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun getCount(): Int {
return if (bannerImageList.size > 0) {
Int.MAX_VALUE
} else {
0
}
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
val viewPager = container as ViewPager
val view = `object` as View
viewPager.removeView(view)
}
interface SliderItemClickListener {
fun onSliderImageClick(item: SliderImagesItem)
}
}
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