onPageSelected isn't triggered when calling setCurrentItem(0)

后端 未结 10 1766
梦如初夏
梦如初夏 2020-12-22 20:13

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

10条回答
  •  无人及你
    2020-12-22 20:31

    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:

    1. 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.

    2. Since you consciously called setCurrentItem(0) and have a refrence to the OnPageChangedListener, dispatch the onPageSelected() by yourself.

    3. 听楼下怎么说...

提交回复
热议问题