FragmentPagerAdapter和FragmentStatePagerAdapter

他们的区别:查看ViewPager切换页面的源码destroyItem方法
1.FragmentPagerAdapter

 @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        if (DEBUG) Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object
                + " v=" + ((Fragment)object).getView());
        mCurTransaction.detach((Fragment)object);
    }

2.FragmentStatePagerAdapter

 @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);
        }
        mSavedState.set(position, fragment.isAdded()
                ? mFragmentManager.saveFragmentInstanceState(fragment) : null);
        mFragments.set(position, null);

        mCurTransaction.remove(fragment);
    }

FragmentPagerAdapter:Transaction.detach(fragment):fragment与activity视图分离
FragmentStatePagerAdapter:Transaction.remove(fragment):回收切换的fragment(回收内存),减少内存消耗。
最后得出结论:如果页面比较少可以用FragmentPagerAdapter,如果页面比较多考虑内存消耗就用FragmentStatePagerAdapter

你可能感兴趣的:(FragmentPagerAdapter和FragmentStatePagerAdapter)