How can I use ViewPager2's registerOnPageChangeCallback
facility to check the position of the currently visible ViewPAger2 fragment? I know this will consists of an if
/when
statement but don't know the correct way to implememnt this.
mViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
if (mViewPager.currentPage) == 0 {
// do something
}
else if (mViewPager.currentPage) == 1 {
// do something
}
else {
// do something
}
super.onPageSelected(position)
}
})
ViewPager2 uses RecyclerView, one of the most used widgets in the Android world, to show collections of items. This is a huge change for the ViewPager API, as RecyclerView is a powerful and robust widget. It supports vertical paging by using LinearLayoutManager.
Steps for implementing viewpager: Adding the ViewPager widget to the XML layout (usually the main_layout). Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class. An adapter populates the pages inside the Viewpager.
to access the internal RecyclerView used inside the ViewPager2 for now, and you can call findViewHolderForAdapterPosition () or findViewHolderForItemId () as usual. I had a custom view implementing a ViewPager which could, in some cases, modify the inner views without having to recompute all of them for a small change.
onPageSelected (int position): When a new page is selected, ViewPager 2 invokes this method. onPageScrollStateChanged (@ScrollState int state): ViewPager 2 invokes this when the scroll state of the current page changes. Now you need to wire your doppelgangerViewPager with the doppelgangerPageChangeCallback so it can start to get the callbacks.
Use the passed position
to know where you are:
mViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
if (position == 0) {
// you are on the first page
}
else if (position == 1) {
// you are on the second page
}
else if (position == 2){
// you are on the third page
}
super.onPageSelected(position)
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With