Is it possible to bind a handler for setOnPageChangeListener to a ViewPager in XML file with the Android Binding functionality?
The demos show onClick events but I
Instead of OnPageChangeListener
, you can use SimpleOnPageChangeListener
and only override the method you're interested in:
@BindingAdapter("onPageChanged")
@JvmStatic
fun addPageChangedListener(viewPager: ViewPager, listener: OnPageChanged) {
viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
listener.onPageChanged(position)
}
})
}
interface OnPageChanged {
fun onPageChanged(position: Int)
}
Layout:
Handler:
fun handlePageChanged(position: Int) {
println("Page changed: $position")
}
As others have pointed out, you may want to be careful not to attach duplicate listeners.