I have three pages (Fragments) inside a ViewPager, however I only want to display a menu item for two of those pages.
The code given in a previous SO answer does not
Kotlin Users,
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
}
})
Update 2020 for ViewPager2
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrollStateChanged(state: Int) {
println(state)
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
println(position)
}
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
println(position)
}
})
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.
}
});
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)
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
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) {
}
});