简体   繁体   中英

ViewPager.OnPageChangeListener giving wrong position

In a fragment i'm using a ViewPager and setting a current item.

mViewPager.setCurrentItem(5);
mViewPager.setAdapter(someAdapter);
mViewPager.addOnPageChangeListener(this);

Now, OnPageChangeListener's method "onPageSelected(int position)" is not giving positon value 4 or 6, but giving 1. I want if current position is set to 10 then position parameter give 11.

Your are writing correct code but not in correct order.

 mViewPager.setAdapter(someAdapter);
 mViewPager.setCurrentItem(5);
 mViewPager.addOnPageChangeListener(this);

you should first set the adapter then tell which position to load in ViewPager .

You could call setCurrentItem() only after calling setAdapter() and wait for the viewpager to complete its loading. There seems no proper way of doing this. A hack is to wait some milliseconds before calling setCurrentItem() -

Reference: Android ViewPager setCurrentItem not working after onResume

An alternative is to call setCurrentItem() in an OnLayoutChangeListener -

https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&groupby=&sort=&id=75309

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM