Kotlin - How to add OnPageChangeListener in ViewPager
Solution 1:
I found it is quite simple, but it took my time as I am new in kotlin. I hope it will save others time one day.
viewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
}
})
or we can implement ViewPager.OnPageChangeListener
in our Activity
or Fragment
then just use viewPager?.addOnPageChangeListener(this)
but make sure to implement overrided methods.
Solution 2:
For ViewPager2 you can do it using OnPageChangeCallBack
,
viewPager2?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
override fun onPageScrollStateChanged(state: Int) {
super.onPageScrollStateChanged(state)
}
override fun onPageScrolled(position: Int,
positionOffset: Float,
positionOffsetPixels: Int) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
}
})
Solution 3:
Since most of the times we need to override only one of three ViewPager.OnPageChangeListener
's methods (usually onPageSelected
), this might be useful to reduce the code:
viewPager?.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
//override only methods you need, not all of them
override fun onPageSelected(position: Int) {
}
})