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 Handler
s, 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()
).