Getting the current position of a ViewPager
I know with the Gallery widget I was able to use getSelectedItemPosition(); to retrieve the current position, however it doesnt seem ViewPager has that.
I know I can setup a listener and retrieve the position when the page is switched. But I want the current view position.
Solution 1:
You can use:
mViewPager.getCurrentItem()
Solution 2:
Create a listener and set it on your viewpager:
/**
* Get the current view position from the ViewPager by
* extending SimpleOnPageChangeListener class and adding your method
*/
public class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
private int currentPage;
@Override
public void onPageSelected(int position) {
currentPage = position;
}
public final int getCurrentPage() {
return currentPage;
}
}
Solution 3:
Update 2019
Now you can set addOnPageChangeListener
on View Pager to Observe change in Page position.
Since you wanted to setup a listener and retrieve the position when the page is switched
mViewPager.addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
pagePosition.setText("" + position + "/" + galleryAdapter!!.count)
}
})