This function is deprecated.
ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .
ViewPager in Android allows the user to flip left and right through pages of data. In our android ViewPager application we'll implement a ViewPager that swipes through three views with different images and texts.
getChildAt(1); will return the current page. But, if you then change back to page 2 (from page 3) your list of children will be in this order page 2, page 3, page 1 which means that ViewPager. getChildAt(1); does not return the current page.
Use the ViewPager.onPageChangeListener
:
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
ViewPager.setOnPageChangeListener
is deprecated now. You now need to use ViewPager.addOnPageChangeListener
instead.
for example,
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
You can also use ViewPager.SimpleOnPageChangeListener
instead of ViewPager.OnPageChangeListener
and override only those methods you want to use.
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
// optional
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
// optional
@Override
public void onPageSelected(int position) { }
// optional
@Override
public void onPageScrollStateChanged(int state) { }
});
Hope this help :)
Edit:
As per android APIs, setOnPageChangeListener (ViewPager.OnPageChangeListener listener)
is deprecated. Please check this url:- Android ViewPager API
For ViewPager2,
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
})
where OnPageChangeCallback
is a static class with three methods:
onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position),
onPageScrollStateChanged(@ScrollState int state)
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