热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PagerAdapter,FragmentPagerAdapter,FragmentStatePagerAdapter

三者的关系比较简单,FragmentPagerAdapter和FragmentStatePagerAdapter都是PagerAdapter的子类,然后PagerAdapter是和

三者的关系比较简单,FragmentPagerAdapter和FragmentStatePagerAdapter都是PagerAdapter的子类,然后PagerAdapter是和ViewPager搭配使用的,FragmentPagerAdapter和FragmentStatePagerAdapter都是用在ViewPager和Fragment搭配的场合。
首先我们来看下PagerAdapter

/**
* Base class providing the adapter to populate pages inside of
* a {@link ViewPager}. You will most likely want to use a more
* specific implementation of this, such as
* {@link android.support.v4.app.FragmentPagerAdapter} or
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*
*

When you implement a PagerAdapter, you must override the following methods
* at minimum:


*

    *
  • {@link #instantiateItem(ViewGroup, int)}

  • *
  • {@link #destroyItem(ViewGroup, int, Object)}

  • *
  • {@link #getCount()}

  • *
  • {@link #isViewFromObject(View, Object)}

  • *

*
*

PagerAdapter is more general than the adapters used for
* {@link android.widget.AdapterView AdapterViews}. Instead of providing a
* View recycling mechanism directly ViewPager uses callbacks to indicate the
* steps taken during an update. A PagerAdapter may implement a form of View
* recycling if desired or use a more sophisticated method of managing page
* Views such as Fragment transactions where each page is represented by its
* own Fragment.


*
*

ViewPager associates each page with a key Object instead of working with
* Views directly. This key is used to track and uniquely identify a given page
* independent of its position in the adapter. A call to the PagerAdapter method
* {@link #startUpdate(ViewGroup)} indicates that the contents of the ViewPager
* are about to change. One or more calls to {@link #instantiateItem(ViewGroup, int)}
* and/or {@link #destroyItem(ViewGroup, int, Object)} will follow, and the end
* of an update will be signaled by a call to {@link #finishUpdate(ViewGroup)}.
* By the time {@link #finishUpdate(ViewGroup) finishUpdate} returns the views
* associated with the key objects returned by
* {@link #instantiateItem(ViewGroup, int) instantiateItem} should be added to
* the parent ViewGroup passed to these methods and the views associated with
* the keys passed to {@link #destroyItem(ViewGroup, int, Object) destroyItem}
* should be removed. The method {@link #isViewFromObject(View, Object)} identifies
* whether a page View is associated with a given key object.


*
*

A very simple PagerAdapter may choose to use the page Views themselves
* as key objects, returning them from {@link #instantiateItem(ViewGroup, int)}
* after creation and adding them to the parent ViewGroup. A matching
* {@link #destroyItem(ViewGroup, int, Object)} implementation would remove the
* View from the parent ViewGroup and {@link #isViewFromObject(View, Object)}
* could be implemented as return view == object;.


*
*

PagerAdapter supports data set changes. Data set changes must occur on the
* main thread and must end with a call to {@link #notifyDataSetChanged()} similar
* to AdapterView adapters derived from {@link android.widget.BaseAdapter}. A data
* set change may involve pages being added, removed, or changing position. The
* ViewPager will keep the current page active provided the adapter implements
* the method {@link #getItemPosition(Object)}.


*/
public abstract class PagerAdapter {
private DataSetObservable mObservable = new DataSetObservable();
public static final int POSITION_UNCHANGED = -1;
public static final int POSITION_NOnE= -2;
/**
* Return the number of views available.
*/
public abstract int getCount();
/**
* Called when a change in the shown pages is going to start being made.
* @param container The containing View which is displaying this adapter's
* page views.
*/
public void startUpdate(ViewGroup container) {
startUpdate((View) container);
}
/**
* Create the page for the given position. The adapter is responsible
* for adding the view to the container given here, although it only
* must ensure this is done by the time it returns from
* {@link #finishUpdate(ViewGroup)}.
*
* @param container The containing View in which the page will be shown.
* @param position The page position to be instantiated.
* @return Returns an Object representing the new page. This does not
* need to be a View, but can be some other container of the page.
*/
public Object instantiateItem(ViewGroup container, int position) {
return instantiateItem((View) container, position);
}
/**
* Remove a page for the given position. The adapter is responsible
* for removing the view from its container, although it only must ensure
* this is done by the time it returns from {@link #finishUpdate(ViewGroup)}.
*
* @param container The containing View from which the page will be removed.
* @param position The page position to be removed.
* @param object The same object that was returned by
* {@link #instantiateItem(View, int)}.
*/
public void destroyItem(ViewGroup container, int position, Object object) {
destroyItem((View) container, position, object);
}
/**
* Called to inform the adapter of which item is currently considered to
* be the "primary", that is the one show to the user as the current page.
*
* @param container The containing View from which the page will be removed.
* @param position The page position that is now the primary.
* @param object The same object that was returned by
* {@link #instantiateItem(View, int)}.
*/
public void setPrimaryItem(ViewGroup container, int position, Object object) {
setPrimaryItem((View) container, position, object);
}
/**
* Called when the a change in the shown pages has been completed. At this
* point you must ensure that all of the pages have actually been added or
* removed from the container as appropriate.
* @param container The containing View which is displaying this adapter's
* page views.
*/
public void finishUpdate(ViewGroup container) {
finishUpdate((View) container);
}
/**
* Called when a change in the shown pages is going to start being made.
* @param container The containing View which is displaying this adapter's
* page views.
*
* @deprecated Use {@link #startUpdate(ViewGroup)}
*/
public void startUpdate(View container) {
}
/**
* Create the page for the given position. The adapter is responsible
* for adding the view to the container given here, although it only
* must ensure this is done by the time it returns from
* {@link #finishUpdate(ViewGroup)}.
*
* @param container The containing View in which the page will be shown.
* @param position The page position to be instantiated.
* @return Returns an Object representing the new page. This does not
* need to be a View, but can be some other container of the page.
*
* @deprecated Use {@link #instantiateItem(ViewGroup, int)}
*/
public Object instantiateItem(View container, int position) {
throw new UnsupportedOperationException(
"Required method instantiateItem was not overridden");
}
/**
* Remove a page for the given position. The adapter is responsible
* for removing the view from its container, although it only must ensure
* this is done by the time it returns from {@link #finishUpdate(View)}.
*
* @param container The containing View from which the page will be removed.
* @param position The page position to be removed.
* @param object The same object that was returned by
* {@link #instantiateItem(View, int)}.
*
* @deprecated Use {@link #destroyItem(ViewGroup, int, Object)}
*/
public void destroyItem(View container, int position, Object object) {
throw new UnsupportedOperationException("Required method destroyItem was not overridden");
}
/**
* Called to inform the adapter of which item is currently considered to
* be the "primary", that is the one show to the user as the current page.
*
* @param container The containing View from which the page will be removed.
* @param position The page position that is now the primary.
* @param object The same object that was returned by
* {@link #instantiateItem(View, int)}.
*
* @deprecated Use {@link #setPrimaryItem(ViewGroup, int, Object)}
*/
public void setPrimaryItem(View container, int position, Object object) {
}
/**
* Called when the a change in the shown pages has been completed. At this
* point you must ensure that all of the pages have actually been added or
* removed from the container as appropriate.
* @param container The containing View which is displaying this adapter's
* page views.
*
* @deprecated Use {@link #finishUpdate(ViewGroup)}
*/
public void finishUpdate(View container) {
}
/**
* Determines whether a page View is associated with a specific key object
* as returned by {@link #instantiateItem(ViewGroup, int)}. This method is
* required for a PagerAdapter to function properly.
*
* @param view Page View to check for association with object
* @param object Object to check for association with view
* @return true if view is associated with the key object object
*/
public abstract boolean isViewFromObject(View view, Object object);
/**
* Save any instance state associated with this adapter and its pages that should be
* restored if the current UI state needs to be reconstructed.
*
* @return Saved state for this adapter
*/
public Parcelable saveState() {
return null;
}
/**
* Restore any instance state associated with this adapter and its pages
* that was previously saved by {@link #saveState()}.
*
* @param state State previously saved by a call to {@link #saveState()}
* @param loader A ClassLoader that should be used to instantiate any restored objects
*/
public void restoreState(Parcelable state, ClassLoader loader) {
}
/**
* Called when the host view is attempting to determine if an item's position
* has changed. Returns {@link #POSITION_UNCHANGED} if the position of the given
* item has not changed or {@link #POSITION_NONE} if the item is no longer present
* in the adapter.
*
*

The default implementation assumes that items will never
* change position and always returns {@link #POSITION_UNCHANGED}.
*
* @param object Object representing an item, previously returned by a call to
* {@link #instantiateItem(View, int)}.
* @return object's new position index from [0, {@link #getCount()}),
* {@link #POSITION_UNCHANGED} if the object's position has not changed,
* or {@link #POSITION_NONE} if the item is no longer present.
*/
public int getItemPosition(Object object) {
return POSITION_UNCHANGED;
}
/**
* This method should be called by the application if the data backing this adapter has changed
* and associated views should update.
*/
public void notifyDataSetChanged() {
mObservable.notifyChanged();
}
/**
* Register an observer to receive callbacks related to the adapter's data changing.
*
* @param observer The {@link android.database.DataSetObserver} which will receive callbacks.
*/
public void registerDataSetObserver(DataSetObserver observer) {
mObservable.registerObserver(observer);
}
/**
* Unregister an observer from callbacks related to the adapter's data changing.
*
* @param observer The {@link android.database.DataSetObserver} which will be unregistered.
*/
public void unregisterDataSetObserver(DataSetObserver observer) {
mObservable.unregisterObserver(observer);
}
/**
* This method may be called by the ViewPager to obtain a title string
* to describe the specified page. This method may return null
* indicating no title for this page. The default implementation returns
* null.
*
* @param position The position of the title requested
* @return A title for the requested page
*/
public CharSequence getPageTitle(int position) {
return null;
}
/**
* Returns the proportional width of a given page as a percentage of the
* ViewPager's measured width from (0.f-1.f]
*
* @param position The position of the page requested
* @return Proportional width for the given page position
*/
public float getPageWidth(int position) {
return 1.f;
}
}

比较重要的当然是我们需要重写的四个方法,在注释中说的非常清楚,我们在使用PagerAdapter时这四个方法必须重写。另外可参阅 ViewPager的那些事——你真了解预加载机制吗?,我们已经解释过了ViewPager在发生变动的时候都会调用populate方法,而在这个方法每次变化之前会调用startUpdate,结束时会调用finishUpdate,而在处理过程中使用预加载机制,会动态的删除或者新建一些Item,这时就会调用instantiateItem和destroyItem。而对于getCount,getItemPosition和notifyDataSetChanged,跟我们最常用的ListView非常类似,在这就不再赘述。在介绍预加载时我们也提到过getPageWidth,setPrimaryItem方法的作用,getPageTitles相信也不用多说。
另外需要额外注意的是两组方法,saveState和restoreState,我们稍后分析FragmentStatePagerAdapter时再详细分析。还有一组就是unregisterDataSetObserver,registerDataSetObserver用来接收adapter的数据变化。
接着我们来查看FragmentPagerAdapter的源码。

* Implementation of {@link android.support.v4.view.PagerAdapter} that
* represents each page as a {@link Fragment} that is persistently
* kept in the fragment manager as long as the user can return to the page.
*
*

This version of the pager is best for use when there are a handful of
* typically more static fragments to be paged through, such as a set of tabs.
* The fragment of each page the user visits will be kept in memory, though its
* view hierarchy may be destroyed when not visible. This can result in using
* a significant amount of memory since fragment instances can hold on to an
* arbitrary amount of state. For larger sets of pages, consider
* {@link FragmentStatePagerAdapter}.
*
*

When using FragmentPagerAdapter the host ViewPager must have a
* valid ID set.


*
*

Subclasses only need to implement {@link #getItem(int)}
* and {@link #getCount()} to have a working adapter.
*
*

Here is an example implementation of a pager containing fragments of
* lists:
*
* {@sample development/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentPagerSupport.java
* complete}
*
*

The R.layout.fragment_pager resource of the top-level fragment is:
*
* {@sample development/samples/Support4Demos/res/layout/fragment_pager.xml
* complete}
*
*

The R.layout.fragment_pager_list resource containing each
* individual fragment's layout is:
*
* {@sample development/samples/Support4Demos/res/layout/fragment_pager_list.xml
* complete}
*/
public abstract class FragmentPagerAdapter extends PagerAdapter {
private static final String TAG = "FragmentPagerAdapter";
private static final boolean DEBUG = false;
private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;
private Fragment mCurrentPrimaryItem = null;
public FragmentPagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
}
/**
* Return the Fragment associated with a specified position.
*/
public abstract Fragment getItem(int position);
@Override
public void startUpdate(ViewGroup container) {
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
final long itemId = getItemId(position);
// Do we already have this fragment?
String name = makeFragmentName(container.getId(), itemId);
Fragment fragment = mFragmentManager.findFragmentByTag(name);
if (fragment != null) {
if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
mCurTransaction.attach(fragment);
} else {
fragment = getItem(position);
if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
mCurTransaction.add(container.getId(), fragment,
makeFragmentName(container.getId(), itemId));
}
if (fragment != mCurrentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
@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);
}
@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() {
return null;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
/**
* Return a unique identifier for the item at the given position.
*
*

The default implementation returns the given position.
* Subclasses should override this method if the positions of items can change.


*
* @param position Position within this adapter
* @return Unique identifier for the item at position
*/
public long getItemId(int position) {
return position;
}
private static String makeFragmentName(int viewId, long id) {
return "android:switcher:" + viewId + ":" + id;
}
}

通过查看注释我们看到FragmentPagerAdapter和FragmentStatePagerAdapter最大的区别是Framgment的对象实例是否销毁,官方也更推荐我们使用FragmentStatePagerAdapter。
FragmentPagerAdapter最重要的是在instantiateItem方法里边把Framgent给attach上,然后在destroyItem里边detach,在finishUpdate里边最终提交整个Transaction。这些都比较明显,也易于理解。另外网上一直盛传的解决预加载的终极方案(至少我个人认为是的),能过Framgent的getView和setUserVisibleHint来组合判断,view不为空,并且可见时网络请求。原理就在这,setPrimaryItem会把当前要显示的Fragment调用setUserVisibleHint(true),而原来的那个mCurrentPrimaryItem.setUserVisibleHint(false)。
最后让我们来查看FragmentStatePagerAdapter的源码。

/**
* Implementation of {@link android.support.v4.view.PagerAdapter} that
* uses a {@link Fragment} to manage each page. This class also handles
* saving and restoring of fragment's state.
*
*

This version of the pager is more useful when there are a large number
* of pages, working more like a list view. When pages are not visible to
* the user, their entire fragment may be destroyed, only keeping the saved
* state of that fragment. This allows the pager to hold on to much less
* memory associated with each visited page as compared to
* {@link FragmentPagerAdapter} at the cost of potentially more overhead when
* switching between pages.
*
*

When using FragmentPagerAdapter the host ViewPager must have a
* valid ID set.


*
*

Subclasses only need to implement {@link #getItem(int)}
* and {@link #getCount()} to have a working adapter.
*
*

Here is an example implementation of a pager containing fragments of
* lists:
*
* {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/FragmentStatePagerSupport.java
* complete}
*
*

The R.layout.fragment_pager resource of the top-level fragment is:
*
* {@sample development/samples/Support13Demos/res/layout/fragment_pager.xml
* complete}
*
*

The R.layout.fragment_pager_list resource containing each
* individual fragment's layout is:
*
* {@sample development/samples/Support13Demos/res/layout/fragment_pager_list.xml
* complete}
*/
public abstract class FragmentStatePagerAdapter extends PagerAdapter {
private static final String TAG = "FragmentStatePagerAdapter";
private static final boolean DEBUG = false;
private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;
private ArrayList mSavedState = new ArrayList();
private ArrayList mFragments = new ArrayList();
private Fragment mCurrentPrimaryItem = null;
public FragmentStatePagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
}
/**
* Return the Fragment associated with a specified position.
*/
public abstract Fragment getItem(int position);
@Override
public void startUpdate(ViewGroup container) {
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// If we already have this item instantiated, there is nothing
// to do. This can happen when we are restoring the entire pager
// from its saved state, where the fragment manager has already
// taken care of restoring the fragments we previously had instantiated.
if (mFragments.size() > position) {
Fragment f = mFragments.get(position);
if (f != null) {
return f;
}
}
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
Fragment fragment = getItem(position);
if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + 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);
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);
}
mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
mFragments.set(position, null);
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) {
state = new Bundle();
Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
mSavedState.toArray(fss);
state.putParcelableArray("states", fss);
}
for (int i=0; i Fragment f = mFragments.get(i);
if (f != null) {
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) {
Bundle bundle = (Bundle)state;
bundle.setClassLoader(loader);
Parcelable[] fss = bundle.getParcelableArray("states");
mSavedState.clear();
mFragments.clear();
if (fss != null) {
for (int i=0; i mSavedState.add((Fragment.SavedState)fss[i]);
}
}
Iterable 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);
}
}
}
}
}
}

前边说过FragmentPagerAdapter和FragmentStatePagerAdapter最大的差别在于是否会销毁Fragment的实例。那么关键的代码肯定是在instantiateItem和destroyItem里边。
我们先来看FragmentPagerAdapter的方法

@Override
public Object instantiateItem(ViewGroup container, int position) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
final long itemId = getItemId(position);
// Do we already have this fragment?
String name = makeFragmentName(container.getId(), itemId);
Fragment fragment = mFragmentManager.findFragmentByTag(name);
if (fragment != null) {
if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
mCurTransaction.attach(fragment);
} else {
fragment = getItem(position);
if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
mCurTransaction.add(container.getId(), fragment,
makeFragmentName(container.getId(), itemId));
}
if (fragment != mCurrentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
@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);
}

只要没有就add,然后一直都是在attach和detach。Fragment一旦加进去就不会被销毁。
再来查看FragmentStatePagerAdapter

@Override
public Object instantiateItem(ViewGroup container, int position) {
// If we already have this item instantiated, there is nothing
// to do. This can happen when we are restoring the entire pager
// from its saved state, where the fragment manager has already
// taken care of restoring the fragments we previously had instantiated.
if (mFragments.size() > position) {
Fragment f = mFragments.get(position);
if (f != null) {
return f;
}
}
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
Fragment fragment = getItem(position);
if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + 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);
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);
}
mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
mFragments.set(position, null);
mCurTransaction.remove(fragment);
}

FragmentStatePagerAdapter另外维护了一个ArrayList类型的 mSavedState 和一个ArrayList mFragments。每个新建一个Fragment时就从mSavedState 里边找到SavedState ,通过setInitialSavedState把状态恢复了,然后再add进来。然后在destroyItem时,先把状态能过saveFragmentInstanceState保存起来,然后再把mFragments里边的对象置空,最后是remove掉了。这就解释了官方说的跟FragmentPagerAdapter最大的差别。

@Override
public Parcelable saveState() {
Bundle state = null;
if (mSavedState.size() > 0) {
state = new Bundle();
Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
mSavedState.toArray(fss);
state.putParcelableArray("states", fss);
}
for (int i=0; i Fragment f = mFragments.get(i);
if (f != null) {
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) {
Bundle bundle = (Bundle)state;
bundle.setClassLoader(loader);
Parcelable[] fss = bundle.getParcelableArray("states");
mSavedState.clear();
mFragments.clear();
if (fss != null) {
for (int i=0; i mSavedState.add((Fragment.SavedState)fss[i]);
}
}
Iterable 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);
}
}
}
}
}

简单来说就是过Bundle把Fragment的FragmentState存储起来。具体的请看后续分析。


推荐阅读
author-avatar
_名花侑主
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有