Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite scrolling in viewpager2

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

like image 778
nikhil lohar Avatar asked Dec 13 '22 09:12

nikhil lohar


1 Answers

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)
}

}

like image 177
Rafiqul Hasan Avatar answered Dec 28 '22 16:12

Rafiqul Hasan