问题
I've one activity with a viewpager with a custom FragmentAdapter.
Here is my adapter code:
this.viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
SparseArray<WeakReference<Fragment>> registeredFragments = new SparseArray<>(4);
@NonNull
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
this.registeredFragments.put(position, new WeakReference<>(fragment));
return fragment;
}
@Override
public int getCount() {
return 4;
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
WeakReference<Fragment> ret = this.registeredFragments.get(position);
if (ret == null || ret.get() == null) {
if (position == 0)
ret = new WeakReference<>(new NewGiveawayStepFragment1());
else if (position == 1)
ret = new WeakReference<>(NewGiveawayStepFragment2.newInstance(getUser().getApiFacade().getProfilePicUrl()));
else if (position == 2)
ret = new WeakReference<>(new NewGiveawayStepFragment3());
else if (position == 3)
ret = new WeakReference<>(NewGiveawayStepFragment4.newInstance(getUser().getApiFacade().getProfilePicUrl()));
}
return ret.get();
}
});
The idea is after the fragments were created i store them into a SparseArray
and avoid recreating them (i know i could have same behavior viewPager.setOffscreenPageLimit();
but it makes the activity take longer to load at first time
This idea was based on this answer:
https://stackoverflow.com/a/15261142/5679560
In a normal happy world everything works fine...
the problem is when user minimize the app -> android decides to saveState and close the app -> them user restores the app...
In this scenario when the user restores the app the pages setOffscreenPageLimit
are never created
So let be more specific:
1-user loads activity
2-user loads viewpage 0
3-user minimizes the app and android close it
4-user restores the app OK
5-user goes to viewpage 1 OK
6-user goes to viewpage 2 instantiateItem
is never called getItem
is never called and a blank page is shown
7-user goes to viewpage 3 instantiateItem
is never called getItem
is never called and a blank page is shown
No exception is thrown. If the user leaves the app at page 1, when it restores page 0,1 and 2 are OK, if he leaves at page 3 then pages 2 and 3 are OK
This is my activity onRestoreInstanceState
@Override
public void onRestoreInstanceState(@Nullable Bundle savedInstanceState) {
this.currentPage = savedInstanceState.getInt("currentPage");
this.ignoreSpam = savedInstanceState.getBoolean("ignoreSpam", false);
super.onRestoreInstanceState(savedInstanceState);
}
Absolutelly nothing special
Does anyone understand why this happens?
来源:https://stackoverflow.com/questions/55446077/instantiateitem-nor-getitem-are-called-on-fragmentpageradapter