FragmentActivity.java revision 12924cf8019d4a584bcc6cd5f1bab7f993aaaf65
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.app.Activity;
20import android.content.Context;
21import android.content.Intent;
22import android.content.res.Configuration;
23import android.content.res.TypedArray;
24import android.os.Bundle;
25import android.os.Handler;
26import android.os.Message;
27import android.os.Parcelable;
28import android.support.v4.util.SparseArrayCompat;
29import android.util.AttributeSet;
30import android.util.Log;
31import android.view.KeyEvent;
32import android.view.Menu;
33import android.view.MenuItem;
34import android.view.View;
35import android.view.Window;
36
37import java.io.FileDescriptor;
38import java.io.PrintWriter;
39import java.util.ArrayList;
40import java.util.HashMap;
41
42/**
43 * Base class for activities that want to use the support-based
44 * {@link android.support.v4.app.Fragment} and
45 * {@link android.support.v4.content.Loader} APIs.
46 *
47 * <p>When using this class as opposed to new platform's built-in fragment
48 * and loader support, you must use the {@link #getSupportFragmentManager()}
49 * and {@link #getSupportLoaderManager()} methods respectively to access
50 * those features.
51 *
52 * <p>Known limitations:</p>
53 * <ul>
54 * <li> <p>When using the &lt;fragment> tag, this implementation can not
55 * use the parent view's ID as the new fragment's ID.  You must explicitly
56 * specify an ID (or tag) in the &lt;fragment>.</p>
57 * <li> <p>Prior to Honeycomb (3.0), an activity's state was saved before pausing.
58 * Fragments are a significant amount of new state, and dynamic enough that one
59 * often wants them to change between pausing and stopping.  These classes
60 * throw an exception if you try to change the fragment state after it has been
61 * saved, to avoid accidental loss of UI state.  However this is too restrictive
62 * prior to Honeycomb, where the state is saved before pausing.  To address this,
63 * when running on platforms prior to Honeycomb an exception will not be thrown
64 * if you change fragments between the state save and the activity being stopped.
65 * This means that in some cases if the activity is restored from its last saved
66 * state, this may be a snapshot slightly before what the user last saw.</p>
67 * </ul>
68 */
69public class FragmentActivity extends Activity {
70    private static final String TAG = "FragmentActivity";
71
72    private static final String FRAGMENTS_TAG = "android:support:fragments";
73
74    // This is the SDK API version of Honeycomb (3.0).
75    private static final int HONEYCOMB = 11;
76
77    static final int MSG_REALLY_STOPPED = 1;
78    static final int MSG_RESUME_PENDING = 2;
79
80    final Handler mHandler = new Handler() {
81        @Override
82        public void handleMessage(Message msg) {
83            switch (msg.what) {
84                case MSG_REALLY_STOPPED:
85                    if (mStopped) {
86                        doReallyStop(false);
87                    }
88                    break;
89                case MSG_RESUME_PENDING:
90                    onResumeFragments();
91                    mFragments.execPendingActions();
92                    break;
93                default:
94                    super.handleMessage(msg);
95            }
96        }
97
98    };
99    final FragmentManagerImpl mFragments = new FragmentManagerImpl();
100
101    boolean mCreated;
102    boolean mResumed;
103    boolean mStopped;
104    boolean mReallyStopped;
105    boolean mRetaining;
106
107    boolean mOptionsMenuInvalidated;
108
109    boolean mCheckedForLoaderManager;
110    boolean mLoadersStarted;
111    SparseArrayCompat<LoaderManagerImpl> mAllLoaderManagers;
112    LoaderManagerImpl mLoaderManager;
113
114    static final class NonConfigurationInstances {
115        Object activity;
116        Object custom;
117        HashMap<String, Object> children;
118        ArrayList<Fragment> fragments;
119        SparseArrayCompat<LoaderManagerImpl> loaders;
120    }
121
122    static class FragmentTag {
123        public static final int[] Fragment = {
124            0x01010003, 0x010100d0, 0x010100d1
125        };
126        public static final int Fragment_id = 1;
127        public static final int Fragment_name = 0;
128        public static final int Fragment_tag = 2;
129    }
130
131    // ------------------------------------------------------------------------
132    // HOOKS INTO ACTIVITY
133    // ------------------------------------------------------------------------
134
135    /**
136     * Dispatch incoming result to the correct fragment.
137     */
138    @Override
139    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
140        int index = requestCode>>16;
141        if (index != 0) {
142            index--;
143            if (mFragments.mActive == null || index < 0 || index >= mFragments.mActive.size()) {
144                Log.w(TAG, "Activity result fragment index out of range: 0x"
145                        + Integer.toHexString(requestCode));
146                return;
147            }
148            Fragment frag = mFragments.mActive.get(index);
149            if (frag == null) {
150                Log.w(TAG, "Activity result no fragment exists for index: 0x"
151                        + Integer.toHexString(requestCode));
152            } else {
153                frag.onActivityResult(requestCode&0xffff, resultCode, data);
154            }
155            return;
156        }
157
158        super.onActivityResult(requestCode, resultCode, data);
159    }
160
161    /**
162     * Take care of popping the fragment back stack or finishing the activity
163     * as appropriate.
164     */
165    public void onBackPressed() {
166        if (!mFragments.popBackStackImmediate()) {
167            finish();
168        }
169    }
170
171    /**
172     * Dispatch configuration change to all fragments.
173     */
174    @Override
175    public void onConfigurationChanged(Configuration newConfig) {
176        super.onConfigurationChanged(newConfig);
177        mFragments.dispatchConfigurationChanged(newConfig);
178    }
179
180    /**
181     * Perform initialization of all fragments and loaders.
182     */
183    @Override
184    protected void onCreate(Bundle savedInstanceState) {
185        mFragments.attachActivity(this);
186        // Old versions of the platform didn't do this!
187        if (getLayoutInflater().getFactory() == null) {
188            getLayoutInflater().setFactory(this);
189        }
190
191        super.onCreate(savedInstanceState);
192
193        NonConfigurationInstances nc = (NonConfigurationInstances)
194                getLastNonConfigurationInstance();
195        if (nc != null) {
196            mAllLoaderManagers = nc.loaders;
197        }
198        if (savedInstanceState != null) {
199            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
200            mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
201        }
202        mFragments.dispatchCreate();
203    }
204
205    /**
206     * Dispatch to Fragment.onCreateOptionsMenu().
207     */
208    @Override
209    public boolean onCreatePanelMenu(int featureId, Menu menu) {
210        if (featureId == Window.FEATURE_OPTIONS_PANEL) {
211            boolean show = super.onCreatePanelMenu(featureId, menu);
212            show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
213            if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
214                return show;
215            }
216            // Prior to Honeycomb, the framework can't invalidate the options
217            // menu, so we must always say we have one in case the app later
218            // invalidates it and needs to have it shown.
219            return true;
220        }
221        return super.onCreatePanelMenu(featureId, menu);
222    }
223
224    /**
225     * Add support for inflating the &lt;fragment> tag.
226     */
227    @Override
228    public View onCreateView(String name, Context context, AttributeSet attrs) {
229        if (!"fragment".equals(name)) {
230            return super.onCreateView(name, context, attrs);
231        }
232
233        String fname = attrs.getAttributeValue(null, "class");
234        TypedArray a =  context.obtainStyledAttributes(attrs, FragmentTag.Fragment);
235        if (fname == null) {
236            fname = a.getString(FragmentTag.Fragment_name);
237        }
238        int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID);
239        String tag = a.getString(FragmentTag.Fragment_tag);
240        a.recycle();
241
242        View parent = null; // NOTE: no way to get parent pre-Honeycomb.
243        int containerId = parent != null ? parent.getId() : 0;
244        if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
245            throw new IllegalArgumentException(attrs.getPositionDescription()
246                    + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
247        }
248
249        // If we restored from a previous state, we may already have
250        // instantiated this fragment from the state and should use
251        // that instance instead of making a new one.
252        Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
253        if (fragment == null && tag != null) {
254            fragment = mFragments.findFragmentByTag(tag);
255        }
256        if (fragment == null && containerId != View.NO_ID) {
257            fragment = mFragments.findFragmentById(containerId);
258        }
259
260        if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
261                + Integer.toHexString(id) + " fname=" + fname
262                + " existing=" + fragment);
263        if (fragment == null) {
264            fragment = Fragment.instantiate(this, fname);
265            fragment.mFromLayout = true;
266            fragment.mFragmentId = id != 0 ? id : containerId;
267            fragment.mContainerId = containerId;
268            fragment.mTag = tag;
269            fragment.mInLayout = true;
270            fragment.mFragmentManager = mFragments;
271            fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
272            mFragments.addFragment(fragment, true);
273
274        } else if (fragment.mInLayout) {
275            // A fragment already exists and it is not one we restored from
276            // previous state.
277            throw new IllegalArgumentException(attrs.getPositionDescription()
278                    + ": Duplicate id 0x" + Integer.toHexString(id)
279                    + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
280                    + " with another fragment for " + fname);
281        } else {
282            // This fragment was retained from a previous instance; get it
283            // going now.
284            fragment.mInLayout = true;
285            // If this fragment is newly instantiated (either right now, or
286            // from last saved state), then give it the attributes to
287            // initialize itself.
288            if (!fragment.mRetaining) {
289                fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
290            }
291            mFragments.moveToState(fragment);
292        }
293
294        if (fragment.mView == null) {
295            throw new IllegalStateException("Fragment " + fname
296                    + " did not create a view.");
297        }
298        if (id != 0) {
299            fragment.mView.setId(id);
300        }
301        if (fragment.mView.getTag() == null) {
302            fragment.mView.setTag(tag);
303        }
304        return fragment.mView;
305    }
306
307    /**
308     * Destroy all fragments and loaders.
309     */
310    @Override
311    protected void onDestroy() {
312        super.onDestroy();
313
314        doReallyStop(false);
315
316        mFragments.dispatchDestroy();
317        if (mLoaderManager != null) {
318            mLoaderManager.doDestroy();
319        }
320    }
321
322    /**
323     * Take care of calling onBackPressed() for pre-Eclair platforms.
324     */
325    @Override
326    public boolean onKeyDown(int keyCode, KeyEvent event) {
327        if (android.os.Build.VERSION.SDK_INT < 5 /* ECLAIR */
328                && keyCode == KeyEvent.KEYCODE_BACK
329                && event.getRepeatCount() == 0) {
330            // Take care of calling this method on earlier versions of
331            // the platform where it doesn't exist.
332            onBackPressed();
333            return true;
334        }
335
336        return super.onKeyDown(keyCode, event);
337    }
338
339    /**
340     * Dispatch onLowMemory() to all fragments.
341     */
342    @Override
343    public void onLowMemory() {
344        super.onLowMemory();
345        mFragments.dispatchLowMemory();
346    }
347
348    /**
349     * Dispatch context and options menu to fragments.
350     */
351    @Override
352    public boolean onMenuItemSelected(int featureId, MenuItem item) {
353        if (super.onMenuItemSelected(featureId, item)) {
354            return true;
355        }
356
357        switch (featureId) {
358            case Window.FEATURE_OPTIONS_PANEL:
359                return mFragments.dispatchOptionsItemSelected(item);
360
361            case Window.FEATURE_CONTEXT_MENU:
362                return mFragments.dispatchContextItemSelected(item);
363
364            default:
365                return false;
366        }
367    }
368
369    /**
370     * Call onOptionsMenuClosed() on fragments.
371     */
372    @Override
373    public void onPanelClosed(int featureId, Menu menu) {
374        switch (featureId) {
375            case Window.FEATURE_OPTIONS_PANEL:
376                mFragments.dispatchOptionsMenuClosed(menu);
377                break;
378        }
379        super.onPanelClosed(featureId, menu);
380    }
381
382    /**
383     * Dispatch onPause() to fragments.
384     */
385    @Override
386    protected void onPause() {
387        super.onPause();
388        mResumed = false;
389        if (mHandler.hasMessages(MSG_RESUME_PENDING)) {
390            mHandler.removeMessages(MSG_RESUME_PENDING);
391            onResumeFragments();
392        }
393        mFragments.dispatchPause();
394    }
395
396    /**
397     * Dispatch onResume() to fragments.  Note that for better inter-operation
398     * with older versions of the platform, at the point of this call the
399     * fragments attached to the activity are <em>not</em> resumed.  This means
400     * that in some cases the previous state may still be saved, not allowing
401     * fragment transactions that modify the state.  To correctly interact
402     * with fragments in their proper state, you should instead override
403     * {@link #onResumeFragments()}.
404     */
405    @Override
406    protected void onResume() {
407        super.onResume();
408        mHandler.sendEmptyMessage(MSG_RESUME_PENDING);
409        mResumed = true;
410        mFragments.execPendingActions();
411    }
412
413    /**
414     * Dispatch onResume() to fragments.
415     */
416    @Override
417    protected void onPostResume() {
418        super.onPostResume();
419        mHandler.removeMessages(MSG_RESUME_PENDING);
420        onResumeFragments();
421        mFragments.execPendingActions();
422    }
423
424    /**
425     * This is the fragment-orientated version of {@link #onResume()} that you
426     * can override to perform operations in the Activity at the same point
427     * where its fragments are resumed.  Be sure to always call through to
428     * the super-class.
429     */
430    protected void onResumeFragments() {
431        mFragments.dispatchResume();
432    }
433
434    /**
435     * Dispatch onPrepareOptionsMenu() to fragments.
436     */
437    @Override
438    public boolean onPreparePanel(int featureId, View view, Menu menu) {
439        if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
440            if (mOptionsMenuInvalidated) {
441                mOptionsMenuInvalidated = false;
442                menu.clear();
443                onCreatePanelMenu(featureId, menu);
444            }
445            boolean goforit = super.onPreparePanel(featureId, view, menu);
446            goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
447            return goforit && menu.hasVisibleItems();
448        }
449        return super.onPreparePanel(featureId, view, menu);
450    }
451
452    /**
453     * Retain all appropriate fragment and loader state.  You can NOT
454     * override this yourself!  Use {@link #onRetainCustomNonConfigurationInstance()}
455     * if you want to retain your own state.
456     */
457    @Override
458    public final Object onRetainNonConfigurationInstance() {
459        if (mStopped) {
460            doReallyStop(true);
461        }
462
463        Object custom = onRetainCustomNonConfigurationInstance();
464
465        ArrayList<Fragment> fragments = mFragments.retainNonConfig();
466        boolean retainLoaders = false;
467        if (mAllLoaderManagers != null) {
468            // prune out any loader managers that were already stopped and so
469            // have nothing useful to retain.
470            for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
471                LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
472                if (lm.mRetaining) {
473                    retainLoaders = true;
474                } else {
475                    lm.doDestroy();
476                    mAllLoaderManagers.removeAt(i);
477                }
478            }
479        }
480        if (fragments == null && !retainLoaders && custom == null) {
481            return null;
482        }
483
484        NonConfigurationInstances nci = new NonConfigurationInstances();
485        nci.activity = null;
486        nci.custom = custom;
487        nci.children = null;
488        nci.fragments = fragments;
489        nci.loaders = mAllLoaderManagers;
490        return nci;
491    }
492
493    /**
494     * Save all appropriate fragment state.
495     */
496    @Override
497    protected void onSaveInstanceState(Bundle outState) {
498        super.onSaveInstanceState(outState);
499        Parcelable p = mFragments.saveAllState();
500        if (p != null) {
501            outState.putParcelable(FRAGMENTS_TAG, p);
502        }
503    }
504
505    /**
506     * Dispatch onStart() to all fragments.  Ensure any created loaders are
507     * now started.
508     */
509    @Override
510    protected void onStart() {
511        super.onStart();
512
513        mStopped = false;
514        mReallyStopped = false;
515        mHandler.removeMessages(MSG_REALLY_STOPPED);
516
517        if (!mCreated) {
518            mCreated = true;
519            mFragments.dispatchActivityCreated();
520        }
521
522        mFragments.noteStateNotSaved();
523        mFragments.execPendingActions();
524
525        if (!mLoadersStarted) {
526            mLoadersStarted = true;
527            if (mLoaderManager != null) {
528                mLoaderManager.doStart();
529            } else if (!mCheckedForLoaderManager) {
530                mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
531            }
532            mCheckedForLoaderManager = true;
533        }
534        // NOTE: HC onStart goes here.
535
536        mFragments.dispatchStart();
537        if (mAllLoaderManagers != null) {
538            for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
539                LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
540                lm.finishRetain();
541                lm.doReportStart();
542            }
543        }
544    }
545
546    /**
547     * Dispatch onStop() to all fragments.  Ensure all loaders are stopped.
548     */
549    @Override
550    protected void onStop() {
551        super.onStop();
552
553        mStopped = true;
554        mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);
555
556        mFragments.dispatchStop();
557    }
558
559    // ------------------------------------------------------------------------
560    // NEW METHODS
561    // ------------------------------------------------------------------------
562
563    /**
564     * Use this instead of {@link #onRetainNonConfigurationInstance()}.
565     * Retrieve later with {@link #getLastCustomNonConfigurationInstance()}.
566     */
567    public Object onRetainCustomNonConfigurationInstance() {
568        return null;
569    }
570
571    /**
572     * Return the value previously returned from
573     * {@link #onRetainCustomNonConfigurationInstance()}.
574     */
575    public Object getLastCustomNonConfigurationInstance() {
576        NonConfigurationInstances nc = (NonConfigurationInstances)
577                getLastNonConfigurationInstance();
578        return nc != null ? nc.custom : null;
579    }
580
581    /**
582     * Invalidate the activity's options menu. This will cause relevant presentations
583     * of the menu to fully update via calls to onCreateOptionsMenu and
584     * onPrepareOptionsMenu the next time the menu is requested.
585     */
586    public void supportInvalidateOptionsMenu() {
587        if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
588            // If we are running on HC or greater, we can use the framework
589            // API to invalidate the options menu.
590            ActivityCompatHoneycomb.invalidateOptionsMenu(this);
591            return;
592        }
593
594        // Whoops, older platform...  we'll use a hack, to manually rebuild
595        // the options menu the next time it is prepared.
596        mOptionsMenuInvalidated = true;
597    }
598
599    /**
600     * Print the Activity's state into the given stream.  This gets invoked if
601     * you run "adb shell dumpsys activity <activity_component_name>".
602     *
603     * @param prefix Desired prefix to prepend at each line of output.
604     * @param fd The raw file descriptor that the dump is being sent to.
605     * @param writer The PrintWriter to which you should dump your state.  This will be
606     * closed for you after you return.
607     * @param args additional arguments to the dump request.
608     */
609    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
610        if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
611            // XXX This can only work if we can call the super-class impl. :/
612            //ActivityCompatHoneycomb.dump(this, prefix, fd, writer, args);
613        }
614        writer.print(prefix); writer.print("Local FragmentActivity ");
615                writer.print(Integer.toHexString(System.identityHashCode(this)));
616                writer.println(" State:");
617        String innerPrefix = prefix + "  ";
618        writer.print(innerPrefix); writer.print("mCreated=");
619                writer.print(mCreated); writer.print("mResumed=");
620                writer.print(mResumed); writer.print(" mStopped=");
621                writer.print(mStopped); writer.print(" mReallyStopped=");
622                writer.println(mReallyStopped);
623        writer.print(innerPrefix); writer.print("mLoadersStarted=");
624                writer.println(mLoadersStarted);
625        if (mLoaderManager != null) {
626            writer.print(prefix); writer.print("Loader Manager ");
627                    writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
628                    writer.println(":");
629            mLoaderManager.dump(prefix + "  ", fd, writer, args);
630        }
631        mFragments.dump(prefix, fd, writer, args);
632    }
633
634    void doReallyStop(boolean retaining) {
635        if (!mReallyStopped) {
636            mReallyStopped = true;
637            mRetaining = retaining;
638            mHandler.removeMessages(MSG_REALLY_STOPPED);
639            onReallyStop();
640        }
641    }
642
643    /**
644     * Pre-HC, we didn't have a way to determine whether an activity was
645     * being stopped for a config change or not until we saw
646     * onRetainNonConfigurationInstance() called after onStop().  However
647     * we need to know this, to know whether to retain fragments.  This will
648     * tell us what we need to know.
649     */
650    void onReallyStop() {
651        if (mLoadersStarted) {
652            mLoadersStarted = false;
653            if (mLoaderManager != null) {
654                if (!mRetaining) {
655                    mLoaderManager.doStop();
656                } else {
657                    mLoaderManager.doRetain();
658                }
659            }
660        }
661
662        mFragments.dispatchReallyStop();
663    }
664
665    // ------------------------------------------------------------------------
666    // FRAGMENT SUPPORT
667    // ------------------------------------------------------------------------
668
669    /**
670     * Called when a fragment is attached to the activity.
671     */
672    public void onAttachFragment(Fragment fragment) {
673    }
674
675    /**
676     * Return the FragmentManager for interacting with fragments associated
677     * with this activity.
678     */
679    public FragmentManager getSupportFragmentManager() {
680        return mFragments;
681    }
682
683    /**
684     * Modifies the standard behavior to allow results to be delivered to fragments.
685     * This imposes a restriction that requestCode be <= 0xffff.
686     */
687    @Override
688    public void startActivityForResult(Intent intent, int requestCode) {
689        if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
690            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
691        }
692        super.startActivityForResult(intent, requestCode);
693    }
694
695    /**
696     * Called by Fragment.startActivityForResult() to implement its behavior.
697     */
698    public void startActivityFromFragment(Fragment fragment, Intent intent,
699            int requestCode) {
700        if (requestCode == -1) {
701            super.startActivityForResult(intent, -1);
702            return;
703        }
704        if ((requestCode&0xffff0000) != 0) {
705            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
706        }
707        super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
708    }
709
710    void invalidateSupportFragmentIndex(int index) {
711        //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
712        if (mAllLoaderManagers != null) {
713            LoaderManagerImpl lm = mAllLoaderManagers.get(index);
714            if (lm != null && !lm.mRetaining) {
715                lm.doDestroy();
716                mAllLoaderManagers.remove(index);
717            }
718        }
719    }
720
721    // ------------------------------------------------------------------------
722    // LOADER SUPPORT
723    // ------------------------------------------------------------------------
724
725    /**
726     * Return the LoaderManager for this fragment, creating it if needed.
727     */
728    public LoaderManager getSupportLoaderManager() {
729        if (mLoaderManager != null) {
730            return mLoaderManager;
731        }
732        mCheckedForLoaderManager = true;
733        mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
734        return mLoaderManager;
735    }
736
737    LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
738        if (mAllLoaderManagers == null) {
739            mAllLoaderManagers = new SparseArrayCompat<LoaderManagerImpl>();
740        }
741        LoaderManagerImpl lm = mAllLoaderManagers.get(index);
742        if (lm == null) {
743            if (create) {
744                lm = new LoaderManagerImpl(this, started);
745                mAllLoaderManagers.put(index, lm);
746            }
747        } else {
748            lm.updateActivity(this);
749        }
750        return lm;
751    }
752}
753