FragmentPagerAdapter.java revision 2d0f75424d03e9c54ff733aedda4382c49c27d36
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.v13.app;
18
19import android.app.Fragment;
20import android.app.FragmentManager;
21import android.app.FragmentTransaction;
22import android.os.Parcelable;
23import android.support.v4.app.FragmentStatePagerAdapter;
24import android.support.v4.view.PagerAdapter;
25import android.util.Log;
26import android.view.View;
27import android.view.ViewGroup;
28
29/**
30 * Implementation of {@link android.support.v4.view.PagerAdapter} that
31 * represents each page as a {@link android.app.Fragment} that is persistently
32 * kept in the fragment manager as long as the user can return to the page.
33 *
34 * <p>This version of the pager is best for use when there are a handful of
35 * typically more static fragments to be paged through, such as a set of tabs.
36 * The fragment of each page the user visits will be kept in memory, though its
37 * view hierarchy may be destroyed when not visible.  This can result in using
38 * a significant amount of memory since fragment instances can hold on to an
39 * arbitrary amount of state.  For larger sets of pages, consider
40 * {@link FragmentStatePagerAdapter}.
41 *
42 * <p>When using FragmentPagerAdapter the host ViewPager must have a
43 * valid ID set.</p>
44 *
45 * <p>Subclasses only need to implement {@link #getItem(int)}
46 * and {@link #getCount()} to have a working adapter.
47 *
48 * <p>Here is an example implementation of a pager containing fragments of
49 * lists:
50 *
51 * {@sample frameworks/support/samples/Support13Demos/src/com/example/android/supportv13/app/FragmentPagerSupport.java
52 *      complete}
53 *
54 * <p>The <code>R.layout.fragment_pager</code> resource of the top-level fragment is:
55 *
56 * {@sample frameworks/support/samples/Support13Demos/res/layout/fragment_pager.xml
57 *      complete}
58 *
59 * <p>The <code>R.layout.fragment_pager_list</code> resource containing each
60 * individual fragment's layout is:
61 *
62 * {@sample frameworks/support/samples/Support13Demos/res/layout/fragment_pager_list.xml
63 *      complete}
64 */
65public abstract class FragmentPagerAdapter extends PagerAdapter {
66    private static final String TAG = "FragmentPagerAdapter";
67    private static final boolean DEBUG = false;
68
69    private final FragmentManager mFragmentManager;
70    private FragmentTransaction mCurTransaction = null;
71    private Fragment mCurrentPrimaryItem = null;
72
73    public FragmentPagerAdapter(FragmentManager fm) {
74        mFragmentManager = fm;
75    }
76
77    /**
78     * Return the Fragment associated with a specified position.
79     */
80    public abstract Fragment getItem(int position);
81
82    @Override
83    public void startUpdate(ViewGroup container) {
84        if (container.getId() == View.NO_ID) {
85            throw new IllegalStateException("ViewPager with adapter " + this
86                    + " requires a view id");
87        }
88    }
89
90    @Override
91    public Object instantiateItem(ViewGroup container, int position) {
92        if (mCurTransaction == null) {
93            mCurTransaction = mFragmentManager.beginTransaction();
94        }
95
96        final long itemId = getItemId(position);
97
98        // Do we already have this fragment?
99        String name = makeFragmentName(container.getId(), itemId);
100        Fragment fragment = mFragmentManager.findFragmentByTag(name);
101        if (fragment != null) {
102            if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
103            mCurTransaction.attach(fragment);
104        } else {
105            fragment = getItem(position);
106            if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
107            mCurTransaction.add(container.getId(), fragment,
108                    makeFragmentName(container.getId(), itemId));
109        }
110        if (fragment != mCurrentPrimaryItem) {
111            fragment.setMenuVisibility(false);
112            FragmentCompat.setUserVisibleHint(fragment, false);
113        }
114
115        return fragment;
116    }
117
118    @Override
119    public void destroyItem(ViewGroup container, int position, Object object) {
120        if (mCurTransaction == null) {
121            mCurTransaction = mFragmentManager.beginTransaction();
122        }
123        if (DEBUG) Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object
124                + " v=" + ((Fragment)object).getView());
125        mCurTransaction.detach((Fragment)object);
126    }
127
128    @Override
129    public void setPrimaryItem(ViewGroup container, int position, Object object) {
130        Fragment fragment = (Fragment)object;
131        if (fragment != mCurrentPrimaryItem) {
132            if (mCurrentPrimaryItem != null) {
133                mCurrentPrimaryItem.setMenuVisibility(false);
134                FragmentCompat.setUserVisibleHint(mCurrentPrimaryItem, false);
135            }
136            if (fragment != null) {
137                fragment.setMenuVisibility(true);
138                FragmentCompat.setUserVisibleHint(fragment, true);
139            }
140            mCurrentPrimaryItem = fragment;
141        }
142    }
143
144    @Override
145    public void finishUpdate(ViewGroup container) {
146        if (mCurTransaction != null) {
147            mCurTransaction.commitAllowingStateLoss();
148            mCurTransaction = null;
149            mFragmentManager.executePendingTransactions();
150        }
151    }
152
153    @Override
154    public boolean isViewFromObject(View view, Object object) {
155        return ((Fragment)object).getView() == view;
156    }
157
158    @Override
159    public Parcelable saveState() {
160        return null;
161    }
162
163    @Override
164    public void restoreState(Parcelable state, ClassLoader loader) {
165    }
166
167    /**
168     * Return a unique identifier for the item at the given position.
169     *
170     * <p>The default implementation returns the given position.
171     * Subclasses should override this method if the positions of items can change.</p>
172     *
173     * @param position Position within this adapter
174     * @return Unique identifier for the item at position
175     */
176    public long getItemId(int position) {
177        return position;
178    }
179
180    private static String makeFragmentName(int viewId, long id) {
181        return "android:switcher:" + viewId + ":" + id;
182    }
183}