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 android.os.Bundle;
20import android.os.Parcelable;
21import android.support.v4.view.PagerAdapter;
22import android.util.Log;
23import android.view.View;
24import android.view.ViewGroup;
25
26import java.util.ArrayList;
27
28/**
29 * Implementation of {@link 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 frameworks/support/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 frameworks/support/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 frameworks/support/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        if (container.getId() == View.NO_ID) {
87            throw new IllegalStateException("ViewPager with adapter " + this
88                    + " requires a view id");
89        }
90    }
91
92    @Override
93    public Object instantiateItem(ViewGroup container, int position) {
94        // If we already have this item instantiated, there is nothing
95        // to do.  This can happen when we are restoring the entire pager
96        // from its saved state, where the fragment manager has already
97        // taken care of restoring the fragments we previously had instantiated.
98        if (mFragments.size() > position) {
99            Fragment f = mFragments.get(position);
100            if (f != null) {
101                return f;
102            }
103        }
104
105        if (mCurTransaction == null) {
106            mCurTransaction = mFragmentManager.beginTransaction();
107        }
108
109        Fragment fragment = getItem(position);
110        if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
111        if (mSavedState.size() > position) {
112            Fragment.SavedState fss = mSavedState.get(position);
113            if (fss != null) {
114                fragment.setInitialSavedState(fss);
115            }
116        }
117        while (mFragments.size() <= position) {
118            mFragments.add(null);
119        }
120        fragment.setMenuVisibility(false);
121        fragment.setUserVisibleHint(false);
122        mFragments.set(position, fragment);
123        mCurTransaction.add(container.getId(), fragment);
124
125        return fragment;
126    }
127
128    @Override
129    public void destroyItem(ViewGroup container, int position, Object object) {
130        Fragment fragment = (Fragment) object;
131
132        if (mCurTransaction == null) {
133            mCurTransaction = mFragmentManager.beginTransaction();
134        }
135        if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
136                + " v=" + ((Fragment)object).getView());
137        while (mSavedState.size() <= position) {
138            mSavedState.add(null);
139        }
140        mSavedState.set(position, fragment.isAdded()
141                ? mFragmentManager.saveFragmentInstanceState(fragment) : null);
142        mFragments.set(position, null);
143
144        mCurTransaction.remove(fragment);
145    }
146
147    @Override
148    public void setPrimaryItem(ViewGroup container, int position, Object object) {
149        Fragment fragment = (Fragment)object;
150        if (fragment != mCurrentPrimaryItem) {
151            if (mCurrentPrimaryItem != null) {
152                mCurrentPrimaryItem.setMenuVisibility(false);
153                mCurrentPrimaryItem.setUserVisibleHint(false);
154            }
155            if (fragment != null) {
156                fragment.setMenuVisibility(true);
157                fragment.setUserVisibleHint(true);
158            }
159            mCurrentPrimaryItem = fragment;
160        }
161    }
162
163    @Override
164    public void finishUpdate(ViewGroup container) {
165        if (mCurTransaction != null) {
166            mCurTransaction.commitNowAllowingStateLoss();
167            mCurTransaction = null;
168        }
169    }
170
171    @Override
172    public boolean isViewFromObject(View view, Object object) {
173        return ((Fragment)object).getView() == view;
174    }
175
176    @Override
177    public Parcelable saveState() {
178        Bundle state = null;
179        if (mSavedState.size() > 0) {
180            state = new Bundle();
181            Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
182            mSavedState.toArray(fss);
183            state.putParcelableArray("states", fss);
184        }
185        for (int i=0; i<mFragments.size(); i++) {
186            Fragment f = mFragments.get(i);
187            if (f != null && f.isAdded()) {
188                if (state == null) {
189                    state = new Bundle();
190                }
191                String key = "f" + i;
192                mFragmentManager.putFragment(state, key, f);
193            }
194        }
195        return state;
196    }
197
198    @Override
199    public void restoreState(Parcelable state, ClassLoader loader) {
200        if (state != null) {
201            Bundle bundle = (Bundle)state;
202            bundle.setClassLoader(loader);
203            Parcelable[] fss = bundle.getParcelableArray("states");
204            mSavedState.clear();
205            mFragments.clear();
206            if (fss != null) {
207                for (int i=0; i<fss.length; i++) {
208                    mSavedState.add((Fragment.SavedState)fss[i]);
209                }
210            }
211            Iterable<String> keys = bundle.keySet();
212            for (String key: keys) {
213                if (key.startsWith("f")) {
214                    int index = Integer.parseInt(key.substring(1));
215                    Fragment f = mFragmentManager.getFragment(bundle, key);
216                    if (f != null) {
217                        while (mFragments.size() <= index) {
218                            mFragments.add(null);
219                        }
220                        f.setMenuVisibility(false);
221                        mFragments.set(index, f);
222                    } else {
223                        Log.w(TAG, "Bad fragment at key " + key);
224                    }
225                }
226            }
227        }
228    }
229}
230