ViewPager re-instantiates items out of order after screen rotation

依然范特西╮ 提交于 2019-12-06 06:37:05

After meticulously debugging the app and looking through the ViewPager source, I found the problem.

The first time the app starts and mViewPager.setAdapter(mPagerAdapter) is called, the pages are instantly initiated and the app works as it should. However, when the phone is rotated, calling setAdapter() postpones instantiating the pages because getWindowToken() returns null as the window is not ready yet. Instantiating is delayed until even after onResume() is called in some loop.

Calling setCurrentItem(1, false) makes the first page the primary page, and as a result it is instantiated before the other pages, resulting in the at-first strange 1->0->2 instantiation.

The solution? Use a Handler to run the setCurrentItem() and load data after the other pages have been instantiated:

new Handler().post(new Runnable() {
    @Override
    public void run() {
        mViewPager.setCurrentItem(1, false);
        cleanupAndShowData();
    }
});

Though I'd normally want to avoid using Handlers, it seems this is the only option I've found thus far, because the pages themselves are added in a looper.

EDIT: Even the above had some issues. I ended up calling mViewPager.setCurrentItem(1, false) only after all pages have been instantiated (in onPageInstantiated()).

actualPos= position%getCount();

If this doesn't help, please give some additional code.

I would also suggest a little modification

mViewPager.setOffscreenPageLimit(2);   //use 2 instead of 3 unless neccessary
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!