Android Event Listener Data Binding for ViewPager

后端 未结 3 1993
猫巷女王i
猫巷女王i 2021-01-02 03:36

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

3条回答
  •  离开以前
    2021-01-02 04:04

    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.

提交回复
热议问题