forked from aosp-mirror/platform_frameworks_base
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFragment.java
More file actions
2290 lines (2097 loc) · 89.6 KB
/
Fragment.java
File metadata and controls
2290 lines (2097 loc) · 89.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.app;
import android.animation.Animator;
import android.annotation.Nullable;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.transition.TransitionSet;
import android.util.AndroidRuntimeException;
import android.util.ArrayMap;
import android.util.AttributeSet;
import android.util.DebugUtils;
import android.util.Log;
import android.util.SparseArray;
import android.util.SuperNotCalledException;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import java.io.FileDescriptor;
import java.io.PrintWriter;
final class FragmentState implements Parcelable {
final String mClassName;
final int mIndex;
final boolean mFromLayout;
final int mFragmentId;
final int mContainerId;
final String mTag;
final boolean mRetainInstance;
final boolean mDetached;
final Bundle mArguments;
Bundle mSavedFragmentState;
Fragment mInstance;
public FragmentState(Fragment frag) {
mClassName = frag.getClass().getName();
mIndex = frag.mIndex;
mFromLayout = frag.mFromLayout;
mFragmentId = frag.mFragmentId;
mContainerId = frag.mContainerId;
mTag = frag.mTag;
mRetainInstance = frag.mRetainInstance;
mDetached = frag.mDetached;
mArguments = frag.mArguments;
}
public FragmentState(Parcel in) {
mClassName = in.readString();
mIndex = in.readInt();
mFromLayout = in.readInt() != 0;
mFragmentId = in.readInt();
mContainerId = in.readInt();
mTag = in.readString();
mRetainInstance = in.readInt() != 0;
mDetached = in.readInt() != 0;
mArguments = in.readBundle();
mSavedFragmentState = in.readBundle();
}
public Fragment instantiate(Activity activity, Fragment parent) {
if (mInstance != null) {
return mInstance;
}
if (mArguments != null) {
mArguments.setClassLoader(activity.getClassLoader());
}
mInstance = Fragment.instantiate(activity, mClassName, mArguments);
if (mSavedFragmentState != null) {
mSavedFragmentState.setClassLoader(activity.getClassLoader());
mInstance.mSavedFragmentState = mSavedFragmentState;
}
mInstance.setIndex(mIndex, parent);
mInstance.mFromLayout = mFromLayout;
mInstance.mRestored = true;
mInstance.mFragmentId = mFragmentId;
mInstance.mContainerId = mContainerId;
mInstance.mTag = mTag;
mInstance.mRetainInstance = mRetainInstance;
mInstance.mDetached = mDetached;
mInstance.mFragmentManager = activity.mFragments;
if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,
"Instantiated fragment " + mInstance);
return mInstance;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mClassName);
dest.writeInt(mIndex);
dest.writeInt(mFromLayout ? 1 : 0);
dest.writeInt(mFragmentId);
dest.writeInt(mContainerId);
dest.writeString(mTag);
dest.writeInt(mRetainInstance ? 1 : 0);
dest.writeInt(mDetached ? 1 : 0);
dest.writeBundle(mArguments);
dest.writeBundle(mSavedFragmentState);
}
public static final Parcelable.Creator<FragmentState> CREATOR
= new Parcelable.Creator<FragmentState>() {
public FragmentState createFromParcel(Parcel in) {
return new FragmentState(in);
}
public FragmentState[] newArray(int size) {
return new FragmentState[size];
}
};
}
/**
* A Fragment is a piece of an application's user interface or behavior
* that can be placed in an {@link Activity}. Interaction with fragments
* is done through {@link FragmentManager}, which can be obtained via
* {@link Activity#getFragmentManager() Activity.getFragmentManager()} and
* {@link Fragment#getFragmentManager() Fragment.getFragmentManager()}.
*
* <p>The Fragment class can be used many ways to achieve a wide variety of
* results. In its core, it represents a particular operation or interface
* that is running within a larger {@link Activity}. A Fragment is closely
* tied to the Activity it is in, and can not be used apart from one. Though
* Fragment defines its own lifecycle, that lifecycle is dependent on its
* activity: if the activity is stopped, no fragments inside of it can be
* started; when the activity is destroyed, all fragments will be destroyed.
*
* <p>All subclasses of Fragment must include a public no-argument constructor.
* The framework will often re-instantiate a fragment class when needed,
* in particular during state restore, and needs to be able to find this
* constructor to instantiate it. If the no-argument constructor is not
* available, a runtime exception will occur in some cases during state
* restore.
*
* <p>Topics covered here:
* <ol>
* <li><a href="#OlderPlatforms">Older Platforms</a>
* <li><a href="#Lifecycle">Lifecycle</a>
* <li><a href="#Layout">Layout</a>
* <li><a href="#BackStack">Back Stack</a>
* </ol>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about using fragments, read the
* <a href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</p>
* </div>
*
* <a name="OlderPlatforms"></a>
* <h3>Older Platforms</h3>
*
* While the Fragment API was introduced in
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, a version of the API
* at is also available for use on older platforms through
* {@link android.support.v4.app.FragmentActivity}. See the blog post
* <a href="http://android-developers.blogspot.com/2011/03/fragments-for-all.html">
* Fragments For All</a> for more details.
*
* <a name="Lifecycle"></a>
* <h3>Lifecycle</h3>
*
* <p>Though a Fragment's lifecycle is tied to its owning activity, it has
* its own wrinkle on the standard activity lifecycle. It includes basic
* activity lifecycle methods such as {@link #onResume}, but also important
* are methods related to interactions with the activity and UI generation.
*
* <p>The core series of lifecycle methods that are called to bring a fragment
* up to resumed state (interacting with the user) are:
*
* <ol>
* <li> {@link #onAttach} called once the fragment is associated with its activity.
* <li> {@link #onCreate} called to do initial creation of the fragment.
* <li> {@link #onCreateView} creates and returns the view hierarchy associated
* with the fragment.
* <li> {@link #onActivityCreated} tells the fragment that its activity has
* completed its own {@link Activity#onCreate Activity.onCreate()}.
* <li> {@link #onViewStateRestored} tells the fragment that all of the saved
* state of its view hierarchy has been restored.
* <li> {@link #onStart} makes the fragment visible to the user (based on its
* containing activity being started).
* <li> {@link #onResume} makes the fragment begin interacting with the user
* (based on its containing activity being resumed).
* </ol>
*
* <p>As a fragment is no longer being used, it goes through a reverse
* series of callbacks:
*
* <ol>
* <li> {@link #onPause} fragment is no longer interacting with the user either
* because its activity is being paused or a fragment operation is modifying it
* in the activity.
* <li> {@link #onStop} fragment is no longer visible to the user either
* because its activity is being stopped or a fragment operation is modifying it
* in the activity.
* <li> {@link #onDestroyView} allows the fragment to clean up resources
* associated with its View.
* <li> {@link #onDestroy} called to do final cleanup of the fragment's state.
* <li> {@link #onDetach} called immediately prior to the fragment no longer
* being associated with its activity.
* </ol>
*
* <a name="Layout"></a>
* <h3>Layout</h3>
*
* <p>Fragments can be used as part of your application's layout, allowing
* you to better modularize your code and more easily adjust your user
* interface to the screen it is running on. As an example, we can look
* at a simple program consisting of a list of items, and display of the
* details of each item.</p>
*
* <p>An activity's layout XML can include <code><fragment></code> tags
* to embed fragment instances inside of the layout. For example, here is
* a simple layout that embeds one fragment:</p>
*
* {@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout}
*
* <p>The layout is installed in the activity in the normal way:</p>
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
* main}
*
* <p>The titles fragment, showing a list of titles, is fairly simple, relying
* on {@link ListFragment} for most of its work. Note the implementation of
* clicking an item: depending on the current activity's layout, it can either
* create and display a new fragment to show the details in-place (more about
* this later), or start a new activity to show the details.</p>
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
* titles}
*
* <p>The details fragment showing the contents of a selected item just
* displays a string of text based on an index of a string array built in to
* the app:</p>
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
* details}
*
* <p>In this case when the user clicks on a title, there is no details
* container in the current activity, so the titles fragment's click code will
* launch a new activity to display the details fragment:</p>
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java
* details_activity}
*
* <p>However the screen may be large enough to show both the list of titles
* and details about the currently selected title. To use such a layout on
* a landscape screen, this alternative layout can be placed under layout-land:</p>
*
* {@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout}
*
* <p>Note how the prior code will adjust to this alternative UI flow: the titles
* fragment will now embed the details fragment inside of this activity, and the
* details activity will finish itself if it is running in a configuration
* where the details can be shown in-place.
*
* <p>When a configuration change causes the activity hosting these fragments
* to restart, its new instance may use a different layout that doesn't
* include the same fragments as the previous layout. In this case all of
* the previous fragments will still be instantiated and running in the new
* instance. However, any that are no longer associated with a <fragment>
* tag in the view hierarchy will not have their content view created
* and will return false from {@link #isInLayout}. (The code here also shows
* how you can determine if a fragment placed in a container is no longer
* running in a layout with that container and avoid creating its view hierarchy
* in that case.)
*
* <p>The attributes of the <fragment> tag are used to control the
* LayoutParams provided when attaching the fragment's view to the parent
* container. They can also be parsed by the fragment in {@link #onInflate}
* as parameters.
*
* <p>The fragment being instantiated must have some kind of unique identifier
* so that it can be re-associated with a previous instance if the parent
* activity needs to be destroyed and recreated. This can be provided these
* ways:
*
* <ul>
* <li>If nothing is explicitly supplied, the view ID of the container will
* be used.
* <li><code>android:tag</code> can be used in <fragment> to provide
* a specific tag name for the fragment.
* <li><code>android:id</code> can be used in <fragment> to provide
* a specific identifier for the fragment.
* </ul>
*
* <a name="BackStack"></a>
* <h3>Back Stack</h3>
*
* <p>The transaction in which fragments are modified can be placed on an
* internal back-stack of the owning activity. When the user presses back
* in the activity, any transactions on the back stack are popped off before
* the activity itself is finished.
*
* <p>For example, consider this simple fragment that is instantiated with
* an integer argument and displays that in a TextView in its UI:</p>
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
* fragment}
*
* <p>A function that creates a new instance of the fragment, replacing
* whatever current fragment instance is being shown and pushing that change
* on to the back stack could be written as:
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java
* add_stack}
*
* <p>After each call to this function, a new entry is on the stack, and
* pressing back will pop it to return the user to whatever previous state
* the activity UI was in.
*/
public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener {
private static final ArrayMap<String, Class<?>> sClassMap =
new ArrayMap<String, Class<?>>();
static final int INVALID_STATE = -1; // Invalid state used as a null value.
static final int INITIALIZING = 0; // Not yet created.
static final int CREATED = 1; // Created.
static final int ACTIVITY_CREATED = 2; // The activity has finished its creation.
static final int STOPPED = 3; // Fully created, not started.
static final int STARTED = 4; // Created and started, not resumed.
static final int RESUMED = 5; // Created started and resumed.
private static final Transition USE_DEFAULT_TRANSITION = new TransitionSet();
int mState = INITIALIZING;
// Non-null if the fragment's view hierarchy is currently animating away,
// meaning we need to wait a bit on completely destroying it. This is the
// animation that is running.
Animator mAnimatingAway;
// If mAnimatingAway != null, this is the state we should move to once the
// animation is done.
int mStateAfterAnimating;
// When instantiated from saved state, this is the saved state.
Bundle mSavedFragmentState;
SparseArray<Parcelable> mSavedViewState;
// Index into active fragment array.
int mIndex = -1;
// Internal unique name for this fragment;
String mWho;
// Construction arguments;
Bundle mArguments;
// Target fragment.
Fragment mTarget;
// For use when retaining a fragment: this is the index of the last mTarget.
int mTargetIndex = -1;
// Target request code.
int mTargetRequestCode;
// True if the fragment is in the list of added fragments.
boolean mAdded;
// If set this fragment is being removed from its activity.
boolean mRemoving;
// True if the fragment is in the resumed state.
boolean mResumed;
// Set to true if this fragment was instantiated from a layout file.
boolean mFromLayout;
// Set to true when the view has actually been inflated in its layout.
boolean mInLayout;
// True if this fragment has been restored from previously saved state.
boolean mRestored;
// Number of active back stack entries this fragment is in.
int mBackStackNesting;
// The fragment manager we are associated with. Set as soon as the
// fragment is used in a transaction; cleared after it has been removed
// from all transactions.
FragmentManagerImpl mFragmentManager;
// Activity this fragment is attached to.
Activity mActivity;
// Private fragment manager for child fragments inside of this one.
FragmentManagerImpl mChildFragmentManager;
// If this Fragment is contained in another Fragment, this is that container.
Fragment mParentFragment;
// The optional identifier for this fragment -- either the container ID if it
// was dynamically added to the view hierarchy, or the ID supplied in
// layout.
int mFragmentId;
// When a fragment is being dynamically added to the view hierarchy, this
// is the identifier of the parent container it is being added to.
int mContainerId;
// The optional named tag for this fragment -- usually used to find
// fragments that are not part of the layout.
String mTag;
// Set to true when the app has requested that this fragment be hidden
// from the user.
boolean mHidden;
// Set to true when the app has requested that this fragment be detached.
boolean mDetached;
// If set this fragment would like its instance retained across
// configuration changes.
boolean mRetainInstance;
// If set this fragment is being retained across the current config change.
boolean mRetaining;
// If set this fragment has menu items to contribute.
boolean mHasMenu;
// Set to true to allow the fragment's menu to be shown.
boolean mMenuVisible = true;
// Used to verify that subclasses call through to super class.
boolean mCalled;
// If app has requested a specific animation, this is the one to use.
int mNextAnim;
// The parent container of the fragment after dynamically added to UI.
ViewGroup mContainer;
// The View generated for this fragment.
View mView;
// Whether this fragment should defer starting until after other fragments
// have been started and their loaders are finished.
boolean mDeferStart;
// Hint provided by the app that this fragment is currently visible to the user.
boolean mUserVisibleHint = true;
LoaderManagerImpl mLoaderManager;
boolean mLoadersStarted;
boolean mCheckedForLoaderManager;
private Transition mEnterTransition = null;
private Transition mReturnTransition = USE_DEFAULT_TRANSITION;
private Transition mExitTransition = null;
private Transition mReenterTransition = USE_DEFAULT_TRANSITION;
private Transition mSharedElementEnterTransition = null;
private Transition mSharedElementReturnTransition = USE_DEFAULT_TRANSITION;
private Boolean mAllowReturnTransitionOverlap;
private Boolean mAllowEnterTransitionOverlap;
SharedElementCallback mEnterTransitionCallback = SharedElementCallback.NULL_CALLBACK;
SharedElementCallback mExitTransitionCallback = SharedElementCallback.NULL_CALLBACK;
/**
* State information that has been retrieved from a fragment instance
* through {@link FragmentManager#saveFragmentInstanceState(Fragment)
* FragmentManager.saveFragmentInstanceState}.
*/
public static class SavedState implements Parcelable {
final Bundle mState;
SavedState(Bundle state) {
mState = state;
}
SavedState(Parcel in, ClassLoader loader) {
mState = in.readBundle();
if (loader != null && mState != null) {
mState.setClassLoader(loader);
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeBundle(mState);
}
public static final Parcelable.ClassLoaderCreator<SavedState> CREATOR
= new Parcelable.ClassLoaderCreator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in, null);
}
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, loader);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/**
* Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when
* there is an instantiation failure.
*/
static public class InstantiationException extends AndroidRuntimeException {
public InstantiationException(String msg, Exception cause) {
super(msg, cause);
}
}
/**
* Default constructor. <strong>Every</strong> fragment must have an
* empty constructor, so it can be instantiated when restoring its
* activity's state. It is strongly recommended that subclasses do not
* have other constructors with parameters, since these constructors
* will not be called when the fragment is re-instantiated; instead,
* arguments can be supplied by the caller with {@link #setArguments}
* and later retrieved by the Fragment with {@link #getArguments}.
*
* <p>Applications should generally not implement a constructor. The
* first place application code can run where the fragment is ready to
* be used is in {@link #onAttach(Activity)}, the point where the fragment
* is actually associated with its activity. Some applications may also
* want to implement {@link #onInflate} to retrieve attributes from a
* layout resource, though should take care here because this happens for
* the fragment is attached to its activity.
*/
public Fragment() {
}
/**
* Like {@link #instantiate(Context, String, Bundle)} but with a null
* argument Bundle.
*/
public static Fragment instantiate(Context context, String fname) {
return instantiate(context, fname, null);
}
/**
* Create a new instance of a Fragment with the given class name. This is
* the same as calling its empty constructor.
*
* @param context The calling context being used to instantiate the fragment.
* This is currently just used to get its ClassLoader.
* @param fname The class name of the fragment to instantiate.
* @param args Bundle of arguments to supply to the fragment, which it
* can retrieve with {@link #getArguments()}. May be null.
* @return Returns a new fragment instance.
* @throws InstantiationException If there is a failure in instantiating
* the given fragment class. This is a runtime exception; it is not
* normally expected to happen.
*/
public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
try {
Class<?> clazz = sClassMap.get(fname);
if (clazz == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = context.getClassLoader().loadClass(fname);
if (!Fragment.class.isAssignableFrom(clazz)) {
throw new InstantiationException("Trying to instantiate a class " + fname
+ " that is not a Fragment", new ClassCastException());
}
sClassMap.put(fname, clazz);
}
Fragment f = (Fragment)clazz.newInstance();
if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.mArguments = args;
}
return f;
} catch (ClassNotFoundException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (java.lang.InstantiationException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (IllegalAccessException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
}
}
final void restoreViewState(Bundle savedInstanceState) {
if (mSavedViewState != null) {
mView.restoreHierarchyState(mSavedViewState);
mSavedViewState = null;
}
mCalled = false;
onViewStateRestored(savedInstanceState);
if (!mCalled) {
throw new SuperNotCalledException("Fragment " + this
+ " did not call through to super.onViewStateRestored()");
}
}
final void setIndex(int index, Fragment parent) {
mIndex = index;
if (parent != null) {
mWho = parent.mWho + ":" + mIndex;
} else {
mWho = "android:fragment:" + mIndex;
}
}
final boolean isInBackStack() {
return mBackStackNesting > 0;
}
/**
* Subclasses can not override equals().
*/
@Override final public boolean equals(Object o) {
return super.equals(o);
}
/**
* Subclasses can not override hashCode().
*/
@Override final public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(128);
DebugUtils.buildShortClassTag(this, sb);
if (mIndex >= 0) {
sb.append(" #");
sb.append(mIndex);
}
if (mFragmentId != 0) {
sb.append(" id=0x");
sb.append(Integer.toHexString(mFragmentId));
}
if (mTag != null) {
sb.append(" ");
sb.append(mTag);
}
sb.append('}');
return sb.toString();
}
/**
* Return the identifier this fragment is known by. This is either
* the android:id value supplied in a layout or the container view ID
* supplied when adding the fragment.
*/
final public int getId() {
return mFragmentId;
}
/**
* Get the tag name of the fragment, if specified.
*/
final public String getTag() {
return mTag;
}
/**
* Supply the construction arguments for this fragment. This can only
* be called before the fragment has been attached to its activity; that
* is, you should call it immediately after constructing the fragment. The
* arguments supplied here will be retained across fragment destroy and
* creation.
*/
public void setArguments(Bundle args) {
if (mIndex >= 0) {
throw new IllegalStateException("Fragment already active");
}
mArguments = args;
}
/**
* Return the arguments supplied to {@link #setArguments}, if any.
*/
final public Bundle getArguments() {
return mArguments;
}
/**
* Set the initial saved state that this Fragment should restore itself
* from when first being constructed, as returned by
* {@link FragmentManager#saveFragmentInstanceState(Fragment)
* FragmentManager.saveFragmentInstanceState}.
*
* @param state The state the fragment should be restored from.
*/
public void setInitialSavedState(SavedState state) {
if (mIndex >= 0) {
throw new IllegalStateException("Fragment already active");
}
mSavedFragmentState = state != null && state.mState != null
? state.mState : null;
}
/**
* Optional target for this fragment. This may be used, for example,
* if this fragment is being started by another, and when done wants to
* give a result back to the first. The target set here is retained
* across instances via {@link FragmentManager#putFragment
* FragmentManager.putFragment()}.
*
* @param fragment The fragment that is the target of this one.
* @param requestCode Optional request code, for convenience if you
* are going to call back with {@link #onActivityResult(int, int, Intent)}.
*/
public void setTargetFragment(Fragment fragment, int requestCode) {
mTarget = fragment;
mTargetRequestCode = requestCode;
}
/**
* Return the target fragment set by {@link #setTargetFragment}.
*/
final public Fragment getTargetFragment() {
return mTarget;
}
/**
* Return the target request code set by {@link #setTargetFragment}.
*/
final public int getTargetRequestCode() {
return mTargetRequestCode;
}
/**
* Return the Activity this fragment is currently associated with.
*/
final public Activity getActivity() {
return mActivity;
}
/**
* Return <code>getActivity().getResources()</code>.
*/
final public Resources getResources() {
if (mActivity == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
return mActivity.getResources();
}
/**
* Return a localized, styled CharSequence from the application's package's
* default string table.
*
* @param resId Resource id for the CharSequence text
*/
public final CharSequence getText(int resId) {
return getResources().getText(resId);
}
/**
* Return a localized string from the application's package's
* default string table.
*
* @param resId Resource id for the string
*/
public final String getString(int resId) {
return getResources().getString(resId);
}
/**
* Return a localized formatted string from the application's package's
* default string table, substituting the format arguments as defined in
* {@link java.util.Formatter} and {@link java.lang.String#format}.
*
* @param resId Resource id for the format string
* @param formatArgs The format arguments that will be used for substitution.
*/
public final String getString(int resId, Object... formatArgs) {
return getResources().getString(resId, formatArgs);
}
/**
* Return the FragmentManager for interacting with fragments associated
* with this fragment's activity. Note that this will be non-null slightly
* before {@link #getActivity()}, during the time from when the fragment is
* placed in a {@link FragmentTransaction} until it is committed and
* attached to its activity.
*
* <p>If this Fragment is a child of another Fragment, the FragmentManager
* returned here will be the parent's {@link #getChildFragmentManager()}.
*/
final public FragmentManager getFragmentManager() {
return mFragmentManager;
}
/**
* Return a private FragmentManager for placing and managing Fragments
* inside of this Fragment.
*/
final public FragmentManager getChildFragmentManager() {
if (mChildFragmentManager == null) {
instantiateChildFragmentManager();
if (mState >= RESUMED) {
mChildFragmentManager.dispatchResume();
} else if (mState >= STARTED) {
mChildFragmentManager.dispatchStart();
} else if (mState >= ACTIVITY_CREATED) {
mChildFragmentManager.dispatchActivityCreated();
} else if (mState >= CREATED) {
mChildFragmentManager.dispatchCreate();
}
}
return mChildFragmentManager;
}
/**
* Returns the parent Fragment containing this Fragment. If this Fragment
* is attached directly to an Activity, returns null.
*/
final public Fragment getParentFragment() {
return mParentFragment;
}
/**
* Return true if the fragment is currently added to its activity.
*/
final public boolean isAdded() {
return mActivity != null && mAdded;
}
/**
* Return true if the fragment has been explicitly detached from the UI.
* That is, {@link FragmentTransaction#detach(Fragment)
* FragmentTransaction.detach(Fragment)} has been used on it.
*/
final public boolean isDetached() {
return mDetached;
}
/**
* Return true if this fragment is currently being removed from its
* activity. This is <em>not</em> whether its activity is finishing, but
* rather whether it is in the process of being removed from its activity.
*/
final public boolean isRemoving() {
return mRemoving;
}
/**
* Return true if the layout is included as part of an activity view
* hierarchy via the <fragment> tag. This will always be true when
* fragments are created through the <fragment> tag, <em>except</em>
* in the case where an old fragment is restored from a previous state and
* it does not appear in the layout of the current state.
*/
final public boolean isInLayout() {
return mInLayout;
}
/**
* Return true if the fragment is in the resumed state. This is true
* for the duration of {@link #onResume()} and {@link #onPause()} as well.
*/
final public boolean isResumed() {
return mResumed;
}
/**
* Return true if the fragment is currently visible to the user. This means
* it: (1) has been added, (2) has its view attached to the window, and
* (3) is not hidden.
*/
final public boolean isVisible() {
return isAdded() && !isHidden() && mView != null
&& mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
}
/**
* Return true if the fragment has been hidden. By default fragments
* are shown. You can find out about changes to this state with
* {@link #onHiddenChanged}. Note that the hidden state is orthogonal
* to other states -- that is, to be visible to the user, a fragment
* must be both started and not hidden.
*/
final public boolean isHidden() {
return mHidden;
}
/**
* Called when the hidden state (as returned by {@link #isHidden()} of
* the fragment has changed. Fragments start out not hidden; this will
* be called whenever the fragment changes state from that.
* @param hidden True if the fragment is now hidden, false if it is not
* visible.
*/
public void onHiddenChanged(boolean hidden) {
}
/**
* Control whether a fragment instance is retained across Activity
* re-creation (such as from a configuration change). This can only
* be used with fragments not in the back stack. If set, the fragment
* lifecycle will be slightly different when an activity is recreated:
* <ul>
* <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
* will be, because the fragment is being detached from its current activity).
* <li> {@link #onCreate(Bundle)} will not be called since the fragment
* is not being re-created.
* <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
* still be called.
* </ul>
*/
public void setRetainInstance(boolean retain) {
if (retain && mParentFragment != null) {
throw new IllegalStateException(
"Can't retain fragements that are nested in other fragments");
}
mRetainInstance = retain;
}
final public boolean getRetainInstance() {
return mRetainInstance;
}
/**
* Report that this fragment would like to participate in populating
* the options menu by receiving a call to {@link #onCreateOptionsMenu}
* and related methods.
*
* @param hasMenu If true, the fragment has menu items to contribute.
*/
public void setHasOptionsMenu(boolean hasMenu) {
if (mHasMenu != hasMenu) {
mHasMenu = hasMenu;
if (isAdded() && !isHidden()) {
mFragmentManager.invalidateOptionsMenu();
}
}
}
/**
* Set a hint for whether this fragment's menu should be visible. This
* is useful if you know that a fragment has been placed in your view
* hierarchy so that the user can not currently seen it, so any menu items
* it has should also not be shown.
*
* @param menuVisible The default is true, meaning the fragment's menu will
* be shown as usual. If false, the user will not see the menu.
*/
public void setMenuVisibility(boolean menuVisible) {
if (mMenuVisible != menuVisible) {
mMenuVisible = menuVisible;
if (mHasMenu && isAdded() && !isHidden()) {
mFragmentManager.invalidateOptionsMenu();
}
}
}