I have an Activity with a ViewPager which displays a bunch of pictures. When it starts the ViewPager\'s position is set based on what the user selected in a previous Activit
Actually I think this is a BUG. I've check the source code of ViewPager and found the only trigger of onPageSelected:
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(item);
}
Above, variable dispatchSelected is determined by code:
final boolean dispatchSelected = mCurItem != item;
//item is what you passed to setCurrentItem(item)
And, variable mCurItem is defined and initialized as:
private int mCurItem; // Index of currently displayed page.
So mCurItem is default to 0. When calling setCurrentItem(0), dispatchSelected will be false thus onPageSelected() will not be dispatched.
Now we should understand why calling setCurrentItem(0) is a problem while setCurrentItem(1, or 2, 3...) is not.
How to solve this problem:
Copy the code of ViewPager to your own project and fix it:
from
final boolean dispatchSelected = mCurItem != item; //the old line
to
final boolean dispatchSelected = mCurItem != item || mFirstLayout; //the new line
then use your own ViewPager.
Since you consciously called setCurrentItem(0) and have a refrence to the OnPageChangedListener, dispatch the onPageSelected() by yourself.
听楼下怎么说...