美文网首页AndroidAndroid内存优化
ViewPager使用详解(三):FragmentStatePa

ViewPager使用详解(三):FragmentStatePa

作者: 枯葉殘秋 | 来源:发表于2016-05-18 12:35 被阅读13265次

    ViewPagerFragment的配合使用,除了FragmentPagerAdapter之外,还有另外一个选择FragmentStatePagerAdapter

    从名称上来看,FragmentStatePagerAdapter多了个状态标志,这表明其与FragmentPagerAdapter的差别应该就是状态的问题了。我们可以通过源代码来了解。

    FragmentStatePagerAdapter相对于FragmentPagerAdapter多了两个全局变量:

        private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
        private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
    
    • mSavedState 保存每个Fragment的状态信息的列表
    • mFragments 保存每个Fragment实例对象的列表

    FragmentStatePagerAdapter添加的方法与FragmentPagerAdapter基本一致,重载的方法则进行了部分调整:

    /**
    * 获取给定位置对应的Fragment。
    *
    * @param position 给定的位置
    * @return 对应的Fragment
    */
    public abstract Fragment getItem(int position);
    
    @Override
    public void startUpdate(ViewGroup container) {
    }
    
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // 获取给定位置的已存在Fragment
        if (mFragments.size() > position) {
            Fragment f = mFragments.get(position);
            if (f != null) {
                return f;
            }
        }
    
        // 创建新事务
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
    
        // 创建给定位置的Fragment
        Fragment fragment = getItem(position);
        if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
        // 读取给定位置的Fragment保存的状态,并用该状态对Fragment进行初始化
        if (mSavedState.size() > position) {
            Fragment.SavedState fss = mSavedState.get(position);
            if (fss != null) {
                fragment.setInitialSavedState(fss);
            }
        }
        while (mFragments.size() <= position) {
            mFragments.add(null);
        }
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
        mFragments.set(position, fragment);
        // 添加Fragment到FragmentManager中
        mCurTransaction.add(container.getId(), fragment);
    
        return fragment;
    }
    
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;
    
        // 创建新事务
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
                + " v=" + ((Fragment)object).getView());
        while (mSavedState.size() <= position) {
            mSavedState.add(null);
        }
        // 保存当前销毁的Fragment的状态
        mSavedState.set(position, fragment.isAdded()
                ? mFragmentManager.saveFragmentInstanceState(fragment) : null);
        mFragments.set(position, null);
        // 移除销毁的Fragment
        mCurTransaction.remove(fragment);
    }
    
    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment)object;
        if (fragment != mCurrentPrimaryItem) {
            // 主要项切换,相关菜单及信息进行切换
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
                mCurrentPrimaryItem.setUserVisibleHint(false);
            }
            if (fragment != null) {
                fragment.setMenuVisibility(true);
                fragment.setUserVisibleHint(true);
            }
            mCurrentPrimaryItem = fragment;
        }
    }
    
    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            // 提交事务
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            // 立即运行等待中事务
            mFragmentManager.executePendingTransactions();
        }
    }
    
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return ((Fragment)object).getView() == view;
    }
    
    @Override
    public Parcelable saveState() {
        Bundle state = null;
        if (mSavedState.size() > 0) {
            // 保存Fragment状态列表
            state = new Bundle();
            Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
            mSavedState.toArray(fss);
            state.putParcelableArray("states", fss);
        }
        // 保存Fragment列表
        for (int i=0; i<mFragments.size(); i++) {
            Fragment f = mFragments.get(i);
            if (f != null && f.isAdded()) {
                if (state == null) {
                    state = new Bundle();
                }
                String key = "f" + i;
                mFragmentManager.putFragment(state, key, f);
            }
        }
        return state;
    }
    
    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        if (state != null) {
            // 读取Fragment状态列表
            Bundle bundle = (Bundle)state;
            bundle.setClassLoader(loader);
            Parcelable[] fss = bundle.getParcelableArray("states");
            mSavedState.clear();
            mFragments.clear();
            if (fss != null) {
                for (int i=0; i<fss.length; i++) {
                    mSavedState.add((Fragment.SavedState)fss[i]);
                }
            }
            // 读取Fragment列表
            Iterable<String> keys = bundle.keySet();
            for (String key: keys) {
                if (key.startsWith("f")) {
                    int index = Integer.parseInt(key.substring(1));
                    Fragment f = mFragmentManager.getFragment(bundle, key);
                    if (f != null) {
                        while (mFragments.size() <= index) {
                            mFragments.add(null);
                        }
                        f.setMenuVisibility(false);
                        mFragments.set(index, f);
                    } else {
                        Log.w(TAG, "Bad fragment at key " + key);
                    }
                }
            }
        }
    }
    

    从源代码中,我们可以清楚了解到FragmentStatePagerAdapterFragmentPagerAdapter的不同:

    1. FragmentStatePagerAdapterFragment实例Fragment状态进行引用保留。
    2. FragmentStatePagerAdapterinstantiateItem方法中,创建新Fragment后,读取对应Fragment状态对其进行初始化设置,并且只使用到add方法。
    3. FragmentStatePagerAdapterdestroyItem方法中,销毁Fragment时,保存其Fragment状态,并且使用remove方法移除Fragment
    4. FragmentStatePagerAdapter重载了saveState方法和restoreState方法,在其中对于Fragment实例列表和Fragment状态列表进行保存和读取。

    我们可以创建个简单应用,并且按照以下逻辑进行操作,查看相关LOG,来进一步了解:

    ①首次进入默认Fragment1:

        I: StatePagerActivity onCreate null
        I: StatePagerActivity onStart
        I: StatePagerActivity onResume
        I: Fragment1 setUserVisibleHint false
        I: Fragment2 setUserVisibleHint false
        I: Fragment1 onAttach
        I: Fragment1 onCreate null
        I: Fragment1 setUserVisibleHint true
        I: Fragment2 onAttach
        I: Fragment2 onCreate null
        I: Fragment2 onCreateView null
        I: Fragment2 onViewCreated
        I: Fragment2 onActivityCreated null
        I: Fragment2 onViewStateRestored null
        I: Fragment1 onCreateView null
        I: Fragment1 onViewCreated
        I: Fragment1 onActivityCreated null
        I: Fragment1 onViewStateRestored null
        I: Fragment1 onStart
        I: Fragment1 onResume
        I: Fragment2 onStart
        I: Fragment2 onResume
    

    ②点击Fragment2:

        I: Fragment3 setUserVisibleHint false
        I: Fragment1 setUserVisibleHint false
        I: Fragment2 setUserVisibleHint true
        I: Fragment3 onAttach
        I: Fragment3 onCreate null
        I: Fragment3 onCreateView null
        I: Fragment3 onViewCreated
        I: Fragment3 onActivityCreated null
        I: Fragment3 onViewStateRestored null
        I: Fragment3 onStart
        I: Fragment3 onResume
    

    ③点击Fragment3:

        I: Fragment1 onSaveInstanceState Bundle[{}]
        I: Fragment4 setUserVisibleHint false
        I: Fragment2 setUserVisibleHint false
        I: Fragment3 setUserVisibleHint true
        I: Fragment4 onAttach
        I: Fragment4 onCreate null
        I: Fragment1 onPause
        I: Fragment1 onStop
        I: Fragment1 onDestroyView
        I: Fragment1 onDestroy
        I: Fragment1 onDetach
        I: Fragment4 onCreateView null
        I: Fragment4 onViewCreated
        I: Fragment4 onActivityCreated null
        I: Fragment4 onViewStateRestored null
        I: Fragment4 onStart
        I: Fragment4 onResume
    

    ④点击Fragment4:

        I: Fragment4 onResume
        I: Fragment2 onSaveInstanceState Bundle[{}]
        I: Fragment5 setUserVisibleHint false
        I: Fragment3 setUserVisibleHint false
        I: Fragment4 setUserVisibleHint true
        I: Fragment5 onAttach
        I: Fragment5 onCreate null
        I: Fragment2 onPause
        I: Fragment2 onStop
        I: Fragment2 onDestroyView
        I: Fragment2 onDestroy
        I: Fragment2 onDetach
        I: Fragment5 onCreateView null
        I: Fragment5 onViewCreated
        I: Fragment5 onActivityCreated null
        I: Fragment5 onViewStateRestored null
        I: Fragment5 onStart
        I: Fragment5 onResume
    

    ⑤点击Fragment5:

        I: Fragment3 onSaveInstanceState Bundle[{}]
        I: Fragment4 setUserVisibleHint false
        I: Fragment5 setUserVisibleHint true
        I: Fragment3 onPause
        I: Fragment3 onStop
        I: Fragment3 onDestroyView
        I: Fragment3 onDestroy
        I: Fragment3 onDetach
    

    ⑥进入后台:

        I: Fragment5 onPause
        I: Fragment4 onPause
        I: StatePagerActivity onPause
        I: Fragment5 onSaveInstanceState Bundle[{}]
        I: Fragment4 onSaveInstanceState Bundle[{}]
        I: StatePagerActivity onSaveInstanceState Bundle[{android:viewHierarchyState=Bundle[{android:views={16908290=android.view.AbsSavedState$1@878ae08, 2131492956=android.view.AbsSavedState$1@878ae08, 2131492957=android.view.AbsSavedState$1@878ae08, 2131492958=android.support.v7.widget.Toolbar$SavedState@298b9a1, 2131492959=android.view.AbsSavedState$1@878ae08, 2131492976=FragmentPager.SavedState{71c47c6 position=4}, 2131492977=HorizontalScrollView.SavedState{e0d1387 scrollPosition=0}}}], android:support:fragments=android.support.v4.app.FragmentManagerState@8eea2b4}]
        I: Fragment5 onStop
        I: Fragment4 onStop
        I: StatePagerActivity onStop
    

    ⑦返回前台:

        I: Fragment5 onStart
        I: Fragment4 onStart
        I: StatePagerActivity onStart
        I: StatePagerActivity onResume
        I: Fragment5 onResume
        I: Fragment4 onResume
    

    ⑧点击Fragment4:

        I: Fragment3 setUserVisibleHint false
        I: Fragment5 setUserVisibleHint false
        I: Fragment4 setUserVisibleHint true
        I: Fragment3 onAttach
        I: Fragment3 onCreate Bundle[{android:user_visible_hint=false}]
        I: Fragment3 onCreateView Bundle[{android:user_visible_hint=false}]
        I: Fragment3 onViewCreated
        I: Fragment3 onActivityCreated Bundle[{android:user_visible_hint=false}]
        I: Fragment3 onViewStateRestored Bundle[{android:user_visible_hint=false}]
        I: Fragment3 onStart
        I: Fragment3 onResume
    

    通过LOG,可以进一步了解到FragmentStatePagerAdapterFragmentPagerAdapter的不同:

    1. FragmentFragmentStatePagerAdapter类的destroyItem方法中被remove时,FragmentonDestroy方法和onDetach方法都被调用到。
    2. 当Fragment重新被add时,Fragment的生命周期全部重新调用,但是savedInstanceState参数保留着之前存储的数据。

    相关文章

      网友评论

      • 1fe067fe5392:1万的阅读量,可是,真的解决了我们的问题了吗?
      • 1fe067fe5392:能不能讲讲如何进行状态保存的?这样还是不会。既然都分析源码了,为什么不写个例子出来?我看源码并不能解决我的问题,我想要的是fragment中如何使用,保存状态
      • 猫猫袁:具体怎么使用啊,直接重写getItem() 和 getCount()方法吗???我这样写并没有销毁fragment
        麻烦博主写的再具体点
        猫猫袁: @枯葉殘秋 我知道了,fragment对象销毁了,但是里面的状态会被pager保存,如果重新创建会新建一个fragment把保存的状态填到里面!
        jackzhang1990:@猫猫袁 本地的数据需要在destroyItem方法中手动的清除,比如:fragments.put(position, null);希望对你有用。
        枯葉殘秋:@猫猫袁 FragmentStatePagerAdapter内部有个ArrayList的,这个会引用你已经创建过的Fragment,所以所谓的创建和销毁,都是只有一次的

      本文标题:ViewPager使用详解(三):FragmentStatePa

      本文链接:https://www.haomeiwen.com/subject/pdlwrttx.html