FragmentStatePagerAdapter.java revision 7dc96cc2410f551eefaa973ddc144146ad72d1ec
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.support.v4.app;
18
19import java.util.ArrayList;
20
21import android.os.Bundle;
22import android.os.Parcelable;
23import android.support.v4.view.PagerAdapter;
24import android.util.Log;
25import android.view.View;
26import android.view.ViewGroup;
27
28/**
29 * Implementation of {@link android.support.v4.view.PagerAdapter} that
30 * uses a {@link Fragment} to manage each page. This class also handles
31 * saving and restoring of fragment's state.
32 *
33 * <p>This version of the pager is more useful when there are a large number
34 * of pages, working more like a list view.  When pages are not visible to
35 * the user, their entire fragment may be destroyed, only keeping the saved
36 * state of that fragment.  This allows the pager to hold on to much less
37 * memory associated with each visited page as compared to
38 * {@link FragmentPagerAdapter} at the cost of potentially more overhead when
39 * switching between pages.
40 *
41 * <p>When using FragmentPagerAdapter the host ViewPager must have a
42 * valid ID set.</p>
43 *
44 * <p>Subclasses only need to implement {@link #getItem(int)}
45 * and {@link #getCount()} to have a working adapter.
46 *
47 * <p>Here is an example implementation of a pager containing fragments of
48 * lists:
49 *
50 * {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/FragmentStatePagerSupport.java
51 *      complete}
52 *
53 * <p>The <code>R.layout.fragment_pager</code> resource of the top-level fragment is:
54 *
55 * {@sample development/samples/Support13Demos/res/layout/fragment_pager.xml
56 *      complete}
57 *
58 * <p>The <code>R.layout.fragment_pager_list</code> resource containing each
59 * individual fragment's layout is:
60 *
61 * {@sample development/samples/Support13Demos/res/layout/fragment_pager_list.xml
62 *      complete}
63 */
64public abstract class FragmentStatePagerAdapter extends PagerAdapter {
65    private static final String TAG = "FragmentStatePagerAdapter";
66    private static final boolean DEBUG = false;
67
68    private final FragmentManager mFragmentManager;
69    private FragmentTransaction mCurTransaction = null;
70
71    private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
72    private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
73    private Fragment mCurrentPrimaryItem = null;
74
75    public FragmentStatePagerAdapter(FragmentManager fm) {
76        mFragmentManager = fm;
77    }
78
79    /**
80     * Return the Fragment associated with a specified position.
81     */
82    public abstract Fragment getItem(int position);
83
84    @Override
85    public void startUpdate(ViewGroup container) {
86    }
87
88    @Override
89    public Object instantiateItem(ViewGroup container, int position) {
90        // If we already have this item instantiated, there is nothing
91        // to do.  This can happen when we are restoring the entire pager
92        // from its saved state, where the fragment manager has already
93        // taken care of restoring the fragments we previously had instantiated.
94        if (mFragments.size() > position) {
95            Fragment f = mFragments.get(position);
96            if (f != null) {
97                return f;
98            }
99        }
100
101        if (mCurTransaction == null) {
102            mCurTransaction = mFragmentManager.beginTransaction();
103        }
104
105        Fragment fragment = getItem(position);
106        if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
107        if (mSavedState.size() > position) {
108            Fragment.SavedState fss = mSavedState.get(position);
109            if (fss != null) {
110                fragment.setInitialSavedState(fss);
111            }
112        }
113        while (mFragments.size() <= position) {
114            mFragments.add(null);
115        }
116        fragment.setMenuVisibility(false);
117        mFragments.set(position, fragment);
118        mCurTransaction.add(container.getId(), fragment);
119
120        return fragment;
121    }
122
123    @Override
124    public void destroyItem(ViewGroup container, int position, Object object) {
125        Fragment fragment = (Fragment)object;
126
127        if (mCurTransaction == null) {
128            mCurTransaction = mFragmentManager.beginTransaction();
129        }
130        if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
131                + " v=" + ((Fragment)object).getView());
132        while (mSavedState.size() <= position) {
133            mSavedState.add(null);
134        }
135        mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
136        mFragments.set(position, null);
137
138        mCurTransaction.remove(fragment);
139    }
140
141    @Override
142    public void setPrimaryItem(ViewGroup container, int position, Object object) {
143        Fragment fragment = (Fragment)object;
144        if (fragment != mCurrentPrimaryItem) {
145            if (mCurrentPrimaryItem != null) {
146                mCurrentPrimaryItem.setMenuVisibility(false);
147            }
148            if (fragment != null) {
149                fragment.setMenuVisibility(true);
150            }
151            mCurrentPrimaryItem = fragment;
152        }
153    }
154
155    @Override
156    public void finishUpdate(ViewGroup container) {
157        if (mCurTransaction != null) {
158            mCurTransaction.commitAllowingStateLoss();
159            mCurTransaction = null;
160            mFragmentManager.executePendingTransactions();
161        }
162    }
163
164    @Override
165    public boolean isViewFromObject(View view, Object object) {
166        return ((Fragment)object).getView() == view;
167    }
168
169    @Override
170    public Parcelable saveState() {
171        Bundle state = null;
172        if (mSavedState.size() > 0) {
173            state = new Bundle();
174            Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
175            mSavedState.toArray(fss);
176            state.putParcelableArray("states", fss);
177        }
178        for (int i=0; i<mFragments.size(); i++) {
179            Fragment f = mFragments.get(i);
180            if (f != null) {
181                if (state == null) {
182                    state = new Bundle();
183                }
184                String key = "f" + i;
185                mFragmentManager.putFragment(state, key, f);
186            }
187        }
188        return state;
189    }
190
191    @Override
192    public void restoreState(Parcelable state, ClassLoader loader) {
193        if (state != null) {
194            Bundle bundle = (Bundle)state;
195            bundle.setClassLoader(loader);
196            Parcelable[] fss = bundle.getParcelableArray("states");
197            mSavedState.clear();
198            mFragments.clear();
199            if (fss != null) {
200                for (int i=0; i<fss.length; i++) {
201                    mSavedState.add((Fragment.SavedState)fss[i]);
202                }
203            }
204            Iterable<String> keys = bundle.keySet();
205            for (String key: keys) {
206                if (key.startsWith("f")) {
207                    int index = Integer.parseInt(key.substring(1));
208                    Fragment f = mFragmentManager.getFragment(bundle, key);
209                    if (f != null) {
210                        while (mFragments.size() <= index) {
211                            mFragments.add(null);
212                        }
213                        f.setMenuVisibility(false);
214                        mFragments.set(index, f);
215                    } else {
216                        Log.w(TAG, "Bad fragment at key " + key);
217                    }
218                }
219            }
220        }
221    }
222}
223