When my Activity
gets recreated via orientation change or if "Don't keep activities" is turned on in developer settings, my ViewPager
that has
FragmentStatePagerAdapter
doesn't recreate fragments.
this is activity onCreate
method:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(this);
presenter.onCreate();
}
this is FragmentStatePager:
public class CustomPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments = new ArrayList<>();
public MyFoodaPagerAdapter(FragmentManager fm) {
super(fm);
}
public void init(List<Fragment> initFrags) {
fragments.addAll(initFrags);
notifyDataSetChanged();
}
public void update(Fragment fragment, int position) {
fragments.set(position, fragment);
notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getItemPosition(Object object) {
if (!fragments.contains(object)) {
return POSITION_NONE; // replace
}
return super.getItemPosition(object);
}
public void clear(){
fragments.clear();
notifyDataSetChanged();
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return "Title "+position; // TODO: 25/10/2017
}
}
Since FragmentStatePagerAdapter
saves currently selected fragment and the one's right next to it, if I only have 2 fragments in pager and Activity gets recreated, changing fragment list and calling notifyDataSetChanged();
doesn't do anything.
getItem(int position)
doesn't get triggered in PagerAdapter
at all after activity gets recreated. If I have 3+ fragments in the pager and 1st one is selected then moving to 3rd page will render that fragment and moving back to 1st fragment will finally render 1st fragment. If I have only 2 fragments in pager then moving between does nothing, they do not get rendered.
Also what I'm seeing after Activity is recreated. FragmentManager
has those 2 fragments with reference numbers lets say (Fragment1@1000) and (Fragment2@1001), when I add new fragments into private List<Fragment> fragments
, (Fragment1@1050) and (Fragment2@1051) in pager adapter and call notifyDataSetChanged()
, fragmentManager does not update its fragments, it will still have those old fragments in.
EDIT: I think I found my problem support FragmentPagerAdapter holds reference to old fragments Which says in short, even in the comments, is to never hold reference to fragments outside of PagerAdapter.