onPageSelected doesn't work for first page

前端 未结 10 2080
[愿得一人]
[愿得一人] 2021-01-30 12:30

My pager adapter ( extends PagerAdepter ) has a textview in it. And I update this textview with MainActivity\'s onPageSelected . Its update textview for position > 0 , but start

10条回答
  •  我在风中等你
    2021-01-30 13:18

    Actually I found a good way based on this answer.

    The problem is that the ViewPager is not fully loaded when the listener is setup, the first page is called but the fragments inside the ViewPager are not fully initialized yet.

    In order to fix that I just keep a variable to know if the first page has been called or not:

    private boolean mFirstPageCalled = false;
    

    Then in the listener:

    @Override
    public void onPageSelected(int position) {
    
        if(mFirstPageCalled) {
            // Do your thing
        } else {
            mFirstPageCalled = true;
        }
    }
    

    The final thing to do is to handle the first page that has been missed, this can be done once the ViewPager has been fully created with:

        mViewPager.post(new Runnable(){
            @Override
            public void run() {
                // Do your thing
            }
        });
    

    In my case I just call back here the current fragment showed and work on it:

    Fragment currentFragment = mPagerAdapter.instantiateItem(mViewPager, mViewPager.getCurrentItem());
    currentFragment.customAction();
    

    The post method is only called once, so perfect to handle the first page case.

提交回复
热议问题