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

前端 未结 6 732
执念已碎
执念已碎 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:24

    The problem is that getItem() in FragmentPageAdapter has a wrong name. It should have been named createItem(). Because the way it works the getItem() is for create fragments and it's not safe to call it to query/find a fragment.

    My recomendation is to make a copy of current FragmentPagerAdapter and change it that way:

    Add:

        public abstract Fragment createFragment(int position);
    

    And change getItem to:

    public Fragment getItem(int position) {
        if(containerId!=null) {
            final long itemId = getItemId(position);
            String name = makeFragmentName(containerId, itemId);
            return mFragmentManager.findFragmentByTag(name);
        } else {
            return null;
        }
    }
    

    Finally add that to instantiateItem:

        if(containerId==null)
            containerId = container.getId();
        else if(containerId!=container.getId())
            throw new RuntimeException("Container id not expected to change");
    

    Complete code at this gist

    I think that this implementation is safer and easier to use and also has same performance from the original adapter from Google engineers.

提交回复
热议问题