Looks like you are using ViewPager2 not the original Viewpager and Viewpager2 does not have Page Change Listeners it instead has Page Change Callbacks
So you are using the wrong method to get notified when a pages is changed.
Instead do something like
var myPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
Toast.makeText(this@MainActivity, "Selected position: ${position}",
Toast.LENGTH_SHORT).show()
}
}
viewpager.registerOnPageChangeCallback(myPageChangeCallback)
Though architecturally a lot of times it is bad form to use a OnPageChangeCallback
as you are likely breaking the encapsulation idea of the Fragment and it can be better to use the lifecycle state change to Resumed
of the Fragment to do things when a page(Fragment) is selected. e.g. put the code in the Fragments onResume
method.
Though in this case of setting the actionbar title it is probably ok architecturally to use a OnPageChangeCallback
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…