This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
FragmentManager.java
3741 lines (3421 loc) · 146 KB
/
FragmentManager.java
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.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources.NotFoundException;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Looper;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.ArraySet;
import android.util.AttributeSet;
import android.util.DebugUtils;
import android.util.Log;
import android.util.LogWriter;
import android.util.Pair;
import android.util.SparseArray;
import android.util.SuperNotCalledException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.android.internal.util.FastPrintWriter;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Interface for interacting with {@link Fragment} objects inside of an
* {@link Activity}
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about using fragments, read the
* <a href="{@docRoot}guide/components/fragments.html">Fragments</a> developer guide.</p>
* </div>
*
* While the FragmentManager 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 androidx.fragment.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.
*
* @deprecated Use the <a href="{@docRoot}tools/extras/support-library.html">Support Library</a>
* {@link androidx.fragment.app.FragmentManager} for consistent behavior across all devices
* and access to <a href="{@docRoot}topic/libraries/architecture/lifecycle.html">Lifecycle</a>.
*/
@Deprecated
public abstract class FragmentManager {
/**
* Representation of an entry on the fragment back stack, as created
* with {@link FragmentTransaction#addToBackStack(String)
* FragmentTransaction.addToBackStack()}. Entries can later be
* retrieved with {@link FragmentManager#getBackStackEntryAt(int)
* FragmentManager.getBackStackEntryAt()}.
*
* <p>Note that you should never hold on to a BackStackEntry object;
* the identifier as returned by {@link #getId} is the only thing that
* will be persisted across activity instances.
*
* @deprecated Use the <a href="{@docRoot}tools/extras/support-library.html">
* Support Library</a> {@link androidx.fragment.app.FragmentManager.BackStackEntry}
*/
@Deprecated
public interface BackStackEntry {
/**
* Return the unique identifier for the entry. This is the only
* representation of the entry that will persist across activity
* instances.
*/
public int getId();
/**
* Get the name that was supplied to
* {@link FragmentTransaction#addToBackStack(String)
* FragmentTransaction.addToBackStack(String)} when creating this entry.
*/
public String getName();
/**
* Return the full bread crumb title resource identifier for the entry,
* or 0 if it does not have one.
*/
public int getBreadCrumbTitleRes();
/**
* Return the short bread crumb title resource identifier for the entry,
* or 0 if it does not have one.
*/
public int getBreadCrumbShortTitleRes();
/**
* Return the full bread crumb title for the entry, or null if it
* does not have one.
*/
public CharSequence getBreadCrumbTitle();
/**
* Return the short bread crumb title for the entry, or null if it
* does not have one.
*/
public CharSequence getBreadCrumbShortTitle();
}
/**
* Interface to watch for changes to the back stack.
*
* @deprecated Use the <a href="{@docRoot}tools/extras/support-library.html">
* Support Library</a>
* {@link androidx.fragment.app.FragmentManager.OnBackStackChangedListener}
*/
@Deprecated
public interface OnBackStackChangedListener {
/**
* Called whenever the contents of the back stack change.
*/
public void onBackStackChanged();
}
/**
* Start a series of edit operations on the Fragments associated with
* this FragmentManager.
*
* <p>Note: A fragment transaction can only be created/committed prior
* to an activity saving its state. If you try to commit a transaction
* after {@link Activity#onSaveInstanceState Activity.onSaveInstanceState()}
* (and prior to a following {@link Activity#onStart Activity.onStart}
* or {@link Activity#onResume Activity.onResume()}, you will get an error.
* This is because the framework takes care of saving your current fragments
* in the state, and if changes are made after the state is saved then they
* will be lost.</p>
*/
public abstract FragmentTransaction beginTransaction();
/** @hide -- remove once prebuilts are in. */
@Deprecated
public FragmentTransaction openTransaction() {
return beginTransaction();
}
/**
* After a {@link FragmentTransaction} is committed with
* {@link FragmentTransaction#commit FragmentTransaction.commit()}, it
* is scheduled to be executed asynchronously on the process's main thread.
* If you want to immediately executing any such pending operations, you
* can call this function (only from the main thread) to do so. Note that
* all callbacks and other related behavior will be done from within this
* call, so be careful about where this is called from.
* <p>
* This also forces the start of any postponed Transactions where
* {@link Fragment#postponeEnterTransition()} has been called.
*
* @return Returns true if there were any pending transactions to be
* executed.
*/
public abstract boolean executePendingTransactions();
/**
* Finds a fragment that was identified by the given id either when inflated
* from XML or as the container ID when added in a transaction. This first
* searches through fragments that are currently added to the manager's
* activity; if no such fragment is found, then all fragments currently
* on the back stack associated with this ID are searched.
* @return The fragment if found or null otherwise.
*/
public abstract Fragment findFragmentById(int id);
/**
* Finds a fragment that was identified by the given tag either when inflated
* from XML or as supplied when added in a transaction. This first
* searches through fragments that are currently added to the manager's
* activity; if no such fragment is found, then all fragments currently
* on the back stack are searched.
* @return The fragment if found or null otherwise.
*/
public abstract Fragment findFragmentByTag(String tag);
/**
* Flag for {@link #popBackStack(String, int)}
* and {@link #popBackStack(int, int)}: If set, and the name or ID of
* a back stack entry has been supplied, then all matching entries will
* be consumed until one that doesn't match is found or the bottom of
* the stack is reached. Otherwise, all entries up to but not including that entry
* will be removed.
*/
public static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
/**
* Pop the top state off the back stack. This function is asynchronous -- it
* enqueues the request to pop, but the action will not be performed until the
* application returns to its event loop.
*/
public abstract void popBackStack();
/**
* Like {@link #popBackStack()}, but performs the operation immediately
* inside of the call. This is like calling {@link #executePendingTransactions()}
* afterwards without forcing the start of postponed Transactions.
* @return Returns true if there was something popped, else false.
*/
public abstract boolean popBackStackImmediate();
/**
* Pop the last fragment transition from the manager's fragment
* back stack. If there is nothing to pop, false is returned.
* This function is asynchronous -- it enqueues the
* request to pop, but the action will not be performed until the application
* returns to its event loop.
*
* @param name If non-null, this is the name of a previous back state
* to look for; if found, all states up to that state will be popped. The
* {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
* the named state itself is popped. If null, only the top state is popped.
* @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
*/
public abstract void popBackStack(String name, int flags);
/**
* Like {@link #popBackStack(String, int)}, but performs the operation immediately
* inside of the call. This is like calling {@link #executePendingTransactions()}
* afterwards without forcing the start of postponed Transactions.
* @return Returns true if there was something popped, else false.
*/
public abstract boolean popBackStackImmediate(String name, int flags);
/**
* Pop all back stack states up to the one with the given identifier.
* This function is asynchronous -- it enqueues the
* request to pop, but the action will not be performed until the application
* returns to its event loop.
*
* @param id Identifier of the stated to be popped. If no identifier exists,
* false is returned.
* The identifier is the number returned by
* {@link FragmentTransaction#commit() FragmentTransaction.commit()}. The
* {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
* the named state itself is popped.
* @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
*/
public abstract void popBackStack(int id, int flags);
/**
* Like {@link #popBackStack(int, int)}, but performs the operation immediately
* inside of the call. This is like calling {@link #executePendingTransactions()}
* afterwards without forcing the start of postponed Transactions.
* @return Returns true if there was something popped, else false.
*/
public abstract boolean popBackStackImmediate(int id, int flags);
/**
* Return the number of entries currently in the back stack.
*/
public abstract int getBackStackEntryCount();
/**
* Return the BackStackEntry at index <var>index</var> in the back stack;
* where the item on the bottom of the stack has index 0.
*/
public abstract BackStackEntry getBackStackEntryAt(int index);
/**
* Add a new listener for changes to the fragment back stack.
*/
public abstract void addOnBackStackChangedListener(OnBackStackChangedListener listener);
/**
* Remove a listener that was previously added with
* {@link #addOnBackStackChangedListener(OnBackStackChangedListener)}.
*/
public abstract void removeOnBackStackChangedListener(OnBackStackChangedListener listener);
/**
* Put a reference to a fragment in a Bundle. This Bundle can be
* persisted as saved state, and when later restoring
* {@link #getFragment(Bundle, String)} will return the current
* instance of the same fragment.
*
* @param bundle The bundle in which to put the fragment reference.
* @param key The name of the entry in the bundle.
* @param fragment The Fragment whose reference is to be stored.
*/
public abstract void putFragment(Bundle bundle, String key, Fragment fragment);
/**
* Retrieve the current Fragment instance for a reference previously
* placed with {@link #putFragment(Bundle, String, Fragment)}.
*
* @param bundle The bundle from which to retrieve the fragment reference.
* @param key The name of the entry in the bundle.
* @return Returns the current Fragment instance that is associated with
* the given reference.
*/
public abstract Fragment getFragment(Bundle bundle, String key);
/**
* Get a list of all fragments that are currently added to the FragmentManager.
* This may include those that are hidden as well as those that are shown.
* This will not include any fragments only in the back stack, or fragments that
* are detached or removed.
* <p>
* The order of the fragments in the list is the order in which they were
* added or attached.
*
* @return A list of all fragments that are added to the FragmentManager.
*/
public abstract List<Fragment> getFragments();
/**
* Save the current instance state of the given Fragment. This can be
* used later when creating a new instance of the Fragment and adding
* it to the fragment manager, to have it create itself to match the
* current state returned here. Note that there are limits on how
* this can be used:
*
* <ul>
* <li>The Fragment must currently be attached to the FragmentManager.
* <li>A new Fragment created using this saved state must be the same class
* type as the Fragment it was created from.
* <li>The saved state can not contain dependencies on other fragments --
* that is it can't use {@link #putFragment(Bundle, String, Fragment)} to
* store a fragment reference because that reference may not be valid when
* this saved state is later used. Likewise the Fragment's target and
* result code are not included in this state.
* </ul>
*
* @param f The Fragment whose state is to be saved.
* @return The generated state. This will be null if there was no
* interesting state created by the fragment.
*/
public abstract Fragment.SavedState saveFragmentInstanceState(Fragment f);
/**
* Returns true if the final {@link Activity#onDestroy() Activity.onDestroy()}
* call has been made on the FragmentManager's Activity, so this instance is now dead.
*/
public abstract boolean isDestroyed();
/**
* Registers a {@link FragmentLifecycleCallbacks} to listen to fragment lifecycle events
* happening in this FragmentManager. All registered callbacks will be automatically
* unregistered when this FragmentManager is destroyed.
*
* @param cb Callbacks to register
* @param recursive true to automatically register this callback for all child FragmentManagers
*/
public abstract void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb,
boolean recursive);
/**
* Unregisters a previously registered {@link FragmentLifecycleCallbacks}. If the callback
* was not previously registered this call has no effect. All registered callbacks will be
* automatically unregistered when this FragmentManager is destroyed.
*
* @param cb Callbacks to unregister
*/
public abstract void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb);
/**
* Return the currently active primary navigation fragment for this FragmentManager.
*
* <p>The primary navigation fragment's
* {@link Fragment#getChildFragmentManager() child FragmentManager} will be called first
* to process delegated navigation actions such as {@link #popBackStack()} if no ID
* or transaction name is provided to pop to.</p>
*
* @return the fragment designated as the primary navigation fragment
*/
public abstract Fragment getPrimaryNavigationFragment();
/**
* Print the FragmentManager's state into the given stream.
*
* @param prefix Text to print at the front of each line.
* @param fd The raw file descriptor that the dump is being sent to.
* @param writer A PrintWriter to which the dump is to be set.
* @param args Additional arguments to the dump request.
*/
public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args);
/**
* Control whether the framework's internal fragment manager debugging
* logs are turned on. If enabled, you will see output in logcat as
* the framework performs fragment operations.
*/
public static void enableDebugLogging(boolean enabled) {
FragmentManagerImpl.DEBUG = enabled;
}
/**
* Invalidate the attached activity's options menu as necessary.
* This may end up being deferred until we move to the resumed state.
*/
public void invalidateOptionsMenu() { }
/**
* Returns {@code true} if the FragmentManager's state has already been saved
* by its host. Any operations that would change saved state should not be performed
* if this method returns true. For example, any popBackStack() method, such as
* {@link #popBackStackImmediate()} or any FragmentTransaction using
* {@link FragmentTransaction#commit()} instead of
* {@link FragmentTransaction#commitAllowingStateLoss()} will change
* the state and will result in an error.
*
* @return true if this FragmentManager's state has already been saved by its host
*/
public abstract boolean isStateSaved();
/**
* Callback interface for listening to fragment state changes that happen
* within a given FragmentManager.
*
* @deprecated Use the <a href="{@docRoot}tools/extras/support-library.html">
* Support Library</a>
* {@link androidx.fragment.app.FragmentManager.FragmentLifecycleCallbacks}
*/
@Deprecated
public abstract static class FragmentLifecycleCallbacks {
/**
* Called right before the fragment's {@link Fragment#onAttach(Context)} method is called.
* This is a good time to inject any required dependencies for the fragment before any of
* the fragment's lifecycle methods are invoked.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
* @param context Context that the Fragment is being attached to
*/
public void onFragmentPreAttached(FragmentManager fm, Fragment f, Context context) {}
/**
* Called after the fragment has been attached to its host. Its host will have had
* <code>onAttachFragment</code> called before this call happens.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
* @param context Context that the Fragment was attached to
*/
public void onFragmentAttached(FragmentManager fm, Fragment f, Context context) {}
/**
* Called right before the fragment's {@link Fragment#onCreate(Bundle)} method is called.
* This is a good time to inject any required dependencies or perform other configuration
* for the fragment.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
* @param savedInstanceState Saved instance bundle from a previous instance
*/
public void onFragmentPreCreated(FragmentManager fm, Fragment f,
Bundle savedInstanceState) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onCreate(Bundle)}. This will only happen once for any given
* fragment instance, though the fragment may be attached and detached multiple times.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
* @param savedInstanceState Saved instance bundle from a previous instance
*/
public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onActivityCreated(Bundle)}. This will only happen once for any given
* fragment instance, though the fragment may be attached and detached multiple times.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
* @param savedInstanceState Saved instance bundle from a previous instance
*/
public void onFragmentActivityCreated(FragmentManager fm, Fragment f,
Bundle savedInstanceState) {}
/**
* Called after the fragment has returned a non-null view from the FragmentManager's
* request to {@link Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}.
*
* @param fm Host FragmentManager
* @param f Fragment that created and owns the view
* @param v View returned by the fragment
* @param savedInstanceState Saved instance bundle from a previous instance
*/
public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v,
Bundle savedInstanceState) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onStart()}.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
*/
public void onFragmentStarted(FragmentManager fm, Fragment f) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onResume()}.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
*/
public void onFragmentResumed(FragmentManager fm, Fragment f) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onPause()}.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
*/
public void onFragmentPaused(FragmentManager fm, Fragment f) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onStop()}.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
*/
public void onFragmentStopped(FragmentManager fm, Fragment f) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onSaveInstanceState(Bundle)}.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
* @param outState Saved state bundle for the fragment
*/
public void onFragmentSaveInstanceState(FragmentManager fm, Fragment f, Bundle outState) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onDestroyView()}.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
*/
public void onFragmentViewDestroyed(FragmentManager fm, Fragment f) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onDestroy()}.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
*/
public void onFragmentDestroyed(FragmentManager fm, Fragment f) {}
/**
* Called after the fragment has returned from the FragmentManager's call to
* {@link Fragment#onDetach()}.
*
* @param fm Host FragmentManager
* @param f Fragment changing state
*/
public void onFragmentDetached(FragmentManager fm, Fragment f) {}
}
}
final class FragmentManagerState implements Parcelable {
FragmentState[] mActive;
int[] mAdded;
BackStackState[] mBackStack;
int mPrimaryNavActiveIndex = -1;
int mNextFragmentIndex;
public FragmentManagerState() {
}
public FragmentManagerState(Parcel in) {
mActive = in.createTypedArray(FragmentState.CREATOR);
mAdded = in.createIntArray();
mBackStack = in.createTypedArray(BackStackState.CREATOR);
mPrimaryNavActiveIndex = in.readInt();
mNextFragmentIndex = in.readInt();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedArray(mActive, flags);
dest.writeIntArray(mAdded);
dest.writeTypedArray(mBackStack, flags);
dest.writeInt(mPrimaryNavActiveIndex);
dest.writeInt(mNextFragmentIndex);
}
public static final @android.annotation.NonNull Parcelable.Creator<FragmentManagerState> CREATOR
= new Parcelable.Creator<FragmentManagerState>() {
public FragmentManagerState createFromParcel(Parcel in) {
return new FragmentManagerState(in);
}
public FragmentManagerState[] newArray(int size) {
return new FragmentManagerState[size];
}
};
}
/**
* Container for fragments associated with an activity.
*/
final class FragmentManagerImpl extends FragmentManager implements LayoutInflater.Factory2 {
static boolean DEBUG = false;
static final String TAG = "FragmentManager";
static final String TARGET_REQUEST_CODE_STATE_TAG = "android:target_req_state";
static final String TARGET_STATE_TAG = "android:target_state";
static final String VIEW_STATE_TAG = "android:view_state";
static final String USER_VISIBLE_HINT_TAG = "android:user_visible_hint";
static class AnimateOnHWLayerIfNeededListener implements Animator.AnimatorListener {
private boolean mShouldRunOnHWLayer = false;
private View mView;
public AnimateOnHWLayerIfNeededListener(final View v) {
if (v == null) {
return;
}
mView = v;
}
@Override
public void onAnimationStart(Animator animation) {
mShouldRunOnHWLayer = shouldRunOnHWLayer(mView, animation);
if (mShouldRunOnHWLayer) {
mView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
}
@Override
public void onAnimationEnd(Animator animation) {
if (mShouldRunOnHWLayer) {
mView.setLayerType(View.LAYER_TYPE_NONE, null);
}
mView = null;
animation.removeListener(this);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}
ArrayList<OpGenerator> mPendingActions;
boolean mExecutingActions;
int mNextFragmentIndex = 0;
@UnsupportedAppUsage
SparseArray<Fragment> mActive;
@UnsupportedAppUsage
final ArrayList<Fragment> mAdded = new ArrayList<>();
ArrayList<BackStackRecord> mBackStack;
ArrayList<Fragment> mCreatedMenus;
// Must be accessed while locked.
ArrayList<BackStackRecord> mBackStackIndices;
ArrayList<Integer> mAvailBackStackIndices;
ArrayList<OnBackStackChangedListener> mBackStackChangeListeners;
final CopyOnWriteArrayList<Pair<FragmentLifecycleCallbacks, Boolean>>
mLifecycleCallbacks = new CopyOnWriteArrayList<>();
int mCurState = Fragment.INITIALIZING;
FragmentHostCallback<?> mHost;
FragmentContainer mContainer;
Fragment mParent;
Fragment mPrimaryNav;
boolean mNeedMenuInvalidate;
@UnsupportedAppUsage
boolean mStateSaved;
boolean mDestroyed;
String mNoTransactionsBecause;
boolean mHavePendingDeferredStart;
// Temporary vars for removing redundant operations in BackStackRecords:
ArrayList<BackStackRecord> mTmpRecords;
ArrayList<Boolean> mTmpIsPop;
ArrayList<Fragment> mTmpAddedFragments;
// Temporary vars for state save and restore.
Bundle mStateBundle = null;
SparseArray<Parcelable> mStateArray = null;
// Postponed transactions.
ArrayList<StartEnterTransitionListener> mPostponedTransactions;
// Prior to O, we allowed executing transactions during fragment manager state changes.
// This is dangerous, but we want to keep from breaking old applications.
boolean mAllowOldReentrantBehavior;
// Saved FragmentManagerNonConfig during saveAllState() and cleared in noteStateNotSaved()
FragmentManagerNonConfig mSavedNonConfig;
Runnable mExecCommit = new Runnable() {
@Override
public void run() {
execPendingActions();
}
};
private void throwException(RuntimeException ex) {
Log.e(TAG, ex.getMessage());
LogWriter logw = new LogWriter(Log.ERROR, TAG);
PrintWriter pw = new FastPrintWriter(logw, false, 1024);
if (mHost != null) {
Log.e(TAG, "Activity state:");
try {
mHost.onDump(" ", null, pw, new String[] { });
} catch (Exception e) {
pw.flush();
Log.e(TAG, "Failed dumping state", e);
}
} else {
Log.e(TAG, "Fragment manager state:");
try {
dump(" ", null, pw, new String[] { });
} catch (Exception e) {
pw.flush();
Log.e(TAG, "Failed dumping state", e);
}
}
pw.flush();
throw ex;
}
static boolean modifiesAlpha(Animator anim) {
if (anim == null) {
return false;
}
if (anim instanceof ValueAnimator) {
ValueAnimator valueAnim = (ValueAnimator) anim;
PropertyValuesHolder[] values = valueAnim.getValues();
for (int i = 0; i < values.length; i++) {
if (("alpha").equals(values[i].getPropertyName())) {
return true;
}
}
} else if (anim instanceof AnimatorSet) {
List<Animator> animList = ((AnimatorSet) anim).getChildAnimations();
for (int i = 0; i < animList.size(); i++) {
if (modifiesAlpha(animList.get(i))) {
return true;
}
}
}
return false;
}
static boolean shouldRunOnHWLayer(View v, Animator anim) {
if (v == null || anim == null) {
return false;
}
return v.getLayerType() == View.LAYER_TYPE_NONE
&& v.hasOverlappingRendering()
&& modifiesAlpha(anim);
}
/**
* Sets the to be animated view on hardware layer during the animation.
*/
private void setHWLayerAnimListenerIfAlpha(final View v, Animator anim) {
if (v == null || anim == null) {
return;
}
if (shouldRunOnHWLayer(v, anim)) {
anim.addListener(new AnimateOnHWLayerIfNeededListener(v));
}
}
@Override
public FragmentTransaction beginTransaction() {
return new BackStackRecord(this);
}
@Override
public boolean executePendingTransactions() {
boolean updates = execPendingActions();
forcePostponedTransactions();
return updates;
}
@Override
public void popBackStack() {
enqueueAction(new PopBackStackState(null, -1, 0), false);
}
@Override
public boolean popBackStackImmediate() {
checkStateLoss();
return popBackStackImmediate(null, -1, 0);
}
@Override
public void popBackStack(String name, int flags) {
enqueueAction(new PopBackStackState(name, -1, flags), false);
}
@Override
public boolean popBackStackImmediate(String name, int flags) {
checkStateLoss();
return popBackStackImmediate(name, -1, flags);
}
@Override
public void popBackStack(int id, int flags) {
if (id < 0) {
throw new IllegalArgumentException("Bad id: " + id);
}
enqueueAction(new PopBackStackState(null, id, flags), false);
}
@Override
public boolean popBackStackImmediate(int id, int flags) {
checkStateLoss();
if (id < 0) {
throw new IllegalArgumentException("Bad id: " + id);
}
return popBackStackImmediate(null, id, flags);
}
/**
* Used by all public popBackStackImmediate methods, this executes pending transactions and
* returns true if the pop action did anything, regardless of what other pending
* transactions did.
*
* @return true if the pop operation did anything or false otherwise.
*/
private boolean popBackStackImmediate(String name, int id, int flags) {
execPendingActions();
ensureExecReady(true);
if (mPrimaryNav != null // We have a primary nav fragment
&& id < 0 // No valid id (since they're local)
&& name == null) { // no name to pop to (since they're local)
final FragmentManager childManager = mPrimaryNav.mChildFragmentManager;
if (childManager != null && childManager.popBackStackImmediate()) {
// We did something, just not to this specific FragmentManager. Return true.
return true;
}
}
boolean executePop = popBackStackState(mTmpRecords, mTmpIsPop, name, id, flags);
if (executePop) {
mExecutingActions = true;
try {
removeRedundantOperationsAndExecute(mTmpRecords, mTmpIsPop);
} finally {
cleanupExec();
}
}
doPendingDeferredStart();
burpActive();
return executePop;
}
@Override
public int getBackStackEntryCount() {
return mBackStack != null ? mBackStack.size() : 0;
}
@Override
public BackStackEntry getBackStackEntryAt(int index) {
return mBackStack.get(index);
}
@Override
public void addOnBackStackChangedListener(OnBackStackChangedListener listener) {
if (mBackStackChangeListeners == null) {
mBackStackChangeListeners = new ArrayList<OnBackStackChangedListener>();
}
mBackStackChangeListeners.add(listener);
}
@Override
public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) {
if (mBackStackChangeListeners != null) {
mBackStackChangeListeners.remove(listener);
}
}
@Override
public void putFragment(Bundle bundle, String key, Fragment fragment) {
if (fragment.mIndex < 0) {
throwException(new IllegalStateException("Fragment " + fragment
+ " is not currently in the FragmentManager"));
}
bundle.putInt(key, fragment.mIndex);
}
@Override
public Fragment getFragment(Bundle bundle, String key) {
int index = bundle.getInt(key, -1);
if (index == -1) {
return null;
}
Fragment f = mActive.get(index);
if (f == null) {
throwException(new IllegalStateException("Fragment no longer exists for key "
+ key + ": index " + index));
}
return f;
}
@Override
public List<Fragment> getFragments() {
if (mAdded.isEmpty()) {
return Collections.EMPTY_LIST;
}
synchronized (mAdded) {
return (List<Fragment>) mAdded.clone();
}
}
@Override
public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) {
if (fragment.mIndex < 0) {
throwException(new IllegalStateException("Fragment " + fragment
+ " is not currently in the FragmentManager"));
}
if (fragment.mState > Fragment.INITIALIZING) {
Bundle result = saveFragmentBasicState(fragment);
return result != null ? new Fragment.SavedState(result) : null;
}
return null;
}
@Override
public boolean isDestroyed() {
return mDestroyed;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(128);
sb.append("FragmentManager{");
sb.append(Integer.toHexString(System.identityHashCode(this)));
sb.append(" in ");
if (mParent != null) {
DebugUtils.buildShortClassTag(mParent, sb);
} else {
DebugUtils.buildShortClassTag(mHost, sb);
}
sb.append("}}");
return sb.toString();
}
@Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
String innerPrefix = prefix + " ";
int N;
if (mActive != null) {
N = mActive.size();
if (N > 0) {