ViewPager and fragments — what's the right way to store fragment's state?

后端 未结 11 1352
遇见更好的自我
遇见更好的自我 2020-11-22 02:21

Fragments seem to be very nice for separation of UI logic into some modules. But along with ViewPager its lifecycle is still misty to me. So Guru thoughts are b

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 02:43

    I came up with this simple and elegant solution. It assumes that the activity is responsible for creating the Fragments, and the Adapter just serves them.

    This is the adapter's code (nothing weird here, except for the fact that mFragments is a list of fragments maintained by the Activity)

    class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
    
        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    
        @Override
        public int getCount() {
            return mFragments.size();
        }
    
        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    
        @Override
        public CharSequence getPageTitle(int position) {
            TabFragment fragment = (TabFragment)mFragments.get(position);
            return fragment.getTitle();
        }
    } 
    

    The whole problem of this thread is getting a reference of the "old" fragments, so I use this code in the Activity's onCreate.

        if (savedInstanceState!=null) {
            if (getSupportFragmentManager().getFragments()!=null) {
                for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                    mFragments.add(fragment);
                }
            }
        }
    

    Of course you can further fine tune this code if needed, for example making sure the fragments are instances of a particular class.

提交回复
热议问题