How to properly handle screen rotation with a ViewPager and nested fragments?

前端 未结 6 685
执念已碎
执念已碎 2021-01-31 03:42

I\'ve got this activity, which holds a fragment. This fragment layout consists of a view pager with several fragments (two, actually).

When the view pager is created, it

6条回答
  •  终归单人心
    2021-01-31 04:03

    Why solutions above so complex? Looks like overkill. I solve it just with replacing old reference to new in class extended from FragmentPagerAdapter

     @Override
    public Object instantiateItem(ViewGroup container, int position) {
        frags[position] = (Fragment) super.instantiateItem(container, position);
        return frags[position];
    }
    

    All adapter's code looks like this

    public class RelationsFragmentsAdapter extends FragmentPagerAdapter {
    
    private final String titles[] = new String[3];
    private final Fragment frags[] = new Fragment[titles.length];
    
    public RelationsFragmentsAdapter(FragmentManager fm) {
        super(fm);
        frags[0] = new FriendsFragment();
        frags[1] = new FriendsRequestFragment();
        frags[2] = new FriendsDeclinedFragment();
    
        Resources resources = AppController.getAppContext().getResources();
    
        titles[0] = resources.getString(R.string.my_friends);
        titles[1] = resources.getString(R.string.my_new_friends);
        titles[2] = resources.getString(R.string.followers);
    }
    
    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }
    
    @Override
    public Fragment getItem(int position) {
        return frags[position];
    }
    
    @Override
    public int getCount() {
        return frags.length;
    }
    
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        frags[position] = (Fragment) super.instantiateItem(container, position);
        return frags[position];
    }
    

    }

提交回复
热议问题