FragmentManager.java revision aa3a5538c003c6098185d1c948e22054e2f27488
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 static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP; 20 21import android.content.Context; 22import android.content.res.Configuration; 23import android.content.res.Resources.NotFoundException; 24import android.content.res.TypedArray; 25import android.os.Build; 26import android.os.Bundle; 27import android.os.Looper; 28import android.os.Parcel; 29import android.os.Parcelable; 30import android.support.annotation.CallSuper; 31import android.support.annotation.IdRes; 32import android.support.annotation.RestrictTo; 33import android.support.annotation.StringRes; 34import android.support.v4.os.BuildCompat; 35import android.support.v4.util.DebugUtils; 36import android.support.v4.util.LogWriter; 37import android.support.v4.util.Pair; 38import android.support.v4.view.LayoutInflaterFactory; 39import android.support.v4.view.ViewCompat; 40import android.util.AttributeSet; 41import android.util.Log; 42import android.util.SparseArray; 43import android.view.LayoutInflater; 44import android.view.Menu; 45import android.view.MenuInflater; 46import android.view.MenuItem; 47import android.view.View; 48import android.view.ViewGroup; 49import android.view.animation.AccelerateInterpolator; 50import android.view.animation.AlphaAnimation; 51import android.view.animation.Animation; 52import android.view.animation.Animation.AnimationListener; 53import android.view.animation.AnimationSet; 54import android.view.animation.AnimationUtils; 55import android.view.animation.DecelerateInterpolator; 56import android.view.animation.Interpolator; 57import android.view.animation.ScaleAnimation; 58 59import java.io.FileDescriptor; 60import java.io.PrintWriter; 61import java.lang.reflect.Field; 62import java.util.ArrayList; 63import java.util.Arrays; 64import java.util.List; 65import java.util.concurrent.CopyOnWriteArrayList; 66 67/** 68 * Static library support version of the framework's {@link android.app.FragmentManager}. 69 * Used to write apps that run on platforms prior to Android 3.0. When running 70 * on Android 3.0 or above, this implementation is still used; it does not try 71 * to switch to the framework's implementation. See the framework {@link FragmentManager} 72 * documentation for a class overview. 73 * 74 * <p>Your activity must derive from {@link FragmentActivity} to use this. From such an activity, 75 * you can acquire the {@link FragmentManager} by calling 76 * {@link FragmentActivity#getSupportFragmentManager}. 77 */ 78public abstract class FragmentManager { 79 /** 80 * Representation of an entry on the fragment back stack, as created 81 * with {@link FragmentTransaction#addToBackStack(String) 82 * FragmentTransaction.addToBackStack()}. Entries can later be 83 * retrieved with {@link FragmentManager#getBackStackEntryAt(int) 84 * FragmentManager.getBackStackEntryAt()}. 85 * 86 * <p>Note that you should never hold on to a BackStackEntry object; 87 * the identifier as returned by {@link #getId} is the only thing that 88 * will be persisted across activity instances. 89 */ 90 public interface BackStackEntry { 91 /** 92 * Return the unique identifier for the entry. This is the only 93 * representation of the entry that will persist across activity 94 * instances. 95 */ 96 public int getId(); 97 98 /** 99 * Get the name that was supplied to 100 * {@link FragmentTransaction#addToBackStack(String) 101 * FragmentTransaction.addToBackStack(String)} when creating this entry. 102 */ 103 public String getName(); 104 105 /** 106 * Return the full bread crumb title resource identifier for the entry, 107 * or 0 if it does not have one. 108 */ 109 @StringRes 110 public int getBreadCrumbTitleRes(); 111 112 /** 113 * Return the short bread crumb title resource identifier for the entry, 114 * or 0 if it does not have one. 115 */ 116 @StringRes 117 public int getBreadCrumbShortTitleRes(); 118 119 /** 120 * Return the full bread crumb title for the entry, or null if it 121 * does not have one. 122 */ 123 public CharSequence getBreadCrumbTitle(); 124 125 /** 126 * Return the short bread crumb title for the entry, or null if it 127 * does not have one. 128 */ 129 public CharSequence getBreadCrumbShortTitle(); 130 } 131 132 /** 133 * Interface to watch for changes to the back stack. 134 */ 135 public interface OnBackStackChangedListener { 136 /** 137 * Called whenever the contents of the back stack change. 138 */ 139 public void onBackStackChanged(); 140 } 141 142 /** 143 * Start a series of edit operations on the Fragments associated with 144 * this FragmentManager. 145 * 146 * <p>Note: A fragment transaction can only be created/committed prior 147 * to an activity saving its state. If you try to commit a transaction 148 * after {@link FragmentActivity#onSaveInstanceState FragmentActivity.onSaveInstanceState()} 149 * (and prior to a following {@link FragmentActivity#onStart FragmentActivity.onStart} 150 * or {@link FragmentActivity#onResume FragmentActivity.onResume()}, you will get an error. 151 * This is because the framework takes care of saving your current fragments 152 * in the state, and if changes are made after the state is saved then they 153 * will be lost.</p> 154 */ 155 public abstract FragmentTransaction beginTransaction(); 156 157 /** 158 * @hide -- remove once prebuilts are in. 159 * @deprecated 160 */ 161 @RestrictTo(LIBRARY_GROUP) 162 @Deprecated 163 public FragmentTransaction openTransaction() { 164 return beginTransaction(); 165 } 166 167 /** 168 * After a {@link FragmentTransaction} is committed with 169 * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it 170 * is scheduled to be executed asynchronously on the process's main thread. 171 * If you want to immediately executing any such pending operations, you 172 * can call this function (only from the main thread) to do so. Note that 173 * all callbacks and other related behavior will be done from within this 174 * call, so be careful about where this is called from. 175 * 176 * <p>If you are committing a single transaction that does not modify the 177 * fragment back stack, strongly consider using 178 * {@link FragmentTransaction#commitNow()} instead. This can help avoid 179 * unwanted side effects when other code in your app has pending committed 180 * transactions that expect different timing.</p> 181 * <p> 182 * This also forces the start of any postponed Transactions where 183 * {@link Fragment#postponeEnterTransition()} has been called. 184 * 185 * @return Returns true if there were any pending transactions to be 186 * executed. 187 */ 188 public abstract boolean executePendingTransactions(); 189 190 /** 191 * Finds a fragment that was identified by the given id either when inflated 192 * from XML or as the container ID when added in a transaction. This first 193 * searches through fragments that are currently added to the manager's 194 * activity; if no such fragment is found, then all fragments currently 195 * on the back stack associated with this ID are searched. 196 * @return The fragment if found or null otherwise. 197 */ 198 public abstract Fragment findFragmentById(@IdRes int id); 199 200 /** 201 * Finds a fragment that was identified by the given tag either when inflated 202 * from XML or as supplied when added in a transaction. This first 203 * searches through fragments that are currently added to the manager's 204 * activity; if no such fragment is found, then all fragments currently 205 * on the back stack are searched. 206 * @return The fragment if found or null otherwise. 207 */ 208 public abstract Fragment findFragmentByTag(String tag); 209 210 /** 211 * Flag for {@link #popBackStack(String, int)} 212 * and {@link #popBackStack(int, int)}: If set, and the name or ID of 213 * a back stack entry has been supplied, then all matching entries will 214 * be consumed until one that doesn't match is found or the bottom of 215 * the stack is reached. Otherwise, all entries up to but not including that entry 216 * will be removed. 217 */ 218 public static final int POP_BACK_STACK_INCLUSIVE = 1<<0; 219 220 /** 221 * Pop the top state off the back stack. Returns true if there was one 222 * to pop, else false. This function is asynchronous -- it enqueues the 223 * request to pop, but the action will not be performed until the application 224 * returns to its event loop. 225 */ 226 public abstract void popBackStack(); 227 228 /** 229 * Like {@link #popBackStack()}, but performs the operation immediately 230 * inside of the call. This is like calling {@link #executePendingTransactions()} 231 * afterwards without forcing the start of postponed Transactions. 232 * @return Returns true if there was something popped, else false. 233 */ 234 public abstract boolean popBackStackImmediate(); 235 236 /** 237 * Pop the last fragment transition from the manager's fragment 238 * back stack. If there is nothing to pop, false is returned. 239 * This function is asynchronous -- it enqueues the 240 * request to pop, but the action will not be performed until the application 241 * returns to its event loop. 242 * 243 * @param name If non-null, this is the name of a previous back state 244 * to look for; if found, all states up to that state will be popped. The 245 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether 246 * the named state itself is popped. If null, only the top state is popped. 247 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. 248 */ 249 public abstract void popBackStack(String name, int flags); 250 251 /** 252 * Like {@link #popBackStack(String, int)}, but performs the operation immediately 253 * inside of the call. This is like calling {@link #executePendingTransactions()} 254 * afterwards without forcing the start of postponed Transactions. 255 * @return Returns true if there was something popped, else false. 256 */ 257 public abstract boolean popBackStackImmediate(String name, int flags); 258 259 /** 260 * Pop all back stack states up to the one with the given identifier. 261 * This function is asynchronous -- it enqueues the 262 * request to pop, but the action will not be performed until the application 263 * returns to its event loop. 264 * 265 * @param id Identifier of the stated to be popped. If no identifier exists, 266 * false is returned. 267 * The identifier is the number returned by 268 * {@link FragmentTransaction#commit() FragmentTransaction.commit()}. The 269 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether 270 * the named state itself is popped. 271 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. 272 */ 273 public abstract void popBackStack(int id, int flags); 274 275 /** 276 * Like {@link #popBackStack(int, int)}, but performs the operation immediately 277 * inside of the call. This is like calling {@link #executePendingTransactions()} 278 * afterwards without forcing the start of postponed Transactions. 279 * @return Returns true if there was something popped, else false. 280 */ 281 public abstract boolean popBackStackImmediate(int id, int flags); 282 283 /** 284 * Return the number of entries currently in the back stack. 285 */ 286 public abstract int getBackStackEntryCount(); 287 288 /** 289 * Return the BackStackEntry at index <var>index</var> in the back stack; 290 * entries start index 0 being the bottom of the stack. 291 */ 292 public abstract BackStackEntry getBackStackEntryAt(int index); 293 294 /** 295 * Add a new listener for changes to the fragment back stack. 296 */ 297 public abstract void addOnBackStackChangedListener(OnBackStackChangedListener listener); 298 299 /** 300 * Remove a listener that was previously added with 301 * {@link #addOnBackStackChangedListener(OnBackStackChangedListener)}. 302 */ 303 public abstract void removeOnBackStackChangedListener(OnBackStackChangedListener listener); 304 305 /** 306 * Put a reference to a fragment in a Bundle. This Bundle can be 307 * persisted as saved state, and when later restoring 308 * {@link #getFragment(Bundle, String)} will return the current 309 * instance of the same fragment. 310 * 311 * @param bundle The bundle in which to put the fragment reference. 312 * @param key The name of the entry in the bundle. 313 * @param fragment The Fragment whose reference is to be stored. 314 */ 315 public abstract void putFragment(Bundle bundle, String key, Fragment fragment); 316 317 /** 318 * Retrieve the current Fragment instance for a reference previously 319 * placed with {@link #putFragment(Bundle, String, Fragment)}. 320 * 321 * @param bundle The bundle from which to retrieve the fragment reference. 322 * @param key The name of the entry in the bundle. 323 * @return Returns the current Fragment instance that is associated with 324 * the given reference. 325 */ 326 public abstract Fragment getFragment(Bundle bundle, String key); 327 328 /** 329 * Get a list of all fragments that have been added to the fragment manager. 330 * 331 * @return The list of all fragments or null if none. 332 * @hide 333 */ 334 @RestrictTo(LIBRARY_GROUP) 335 public abstract List<Fragment> getFragments(); 336 337 /** 338 * Save the current instance state of the given Fragment. This can be 339 * used later when creating a new instance of the Fragment and adding 340 * it to the fragment manager, to have it create itself to match the 341 * current state returned here. Note that there are limits on how 342 * this can be used: 343 * 344 * <ul> 345 * <li>The Fragment must currently be attached to the FragmentManager. 346 * <li>A new Fragment created using this saved state must be the same class 347 * type as the Fragment it was created from. 348 * <li>The saved state can not contain dependencies on other fragments -- 349 * that is it can't use {@link #putFragment(Bundle, String, Fragment)} to 350 * store a fragment reference because that reference may not be valid when 351 * this saved state is later used. Likewise the Fragment's target and 352 * result code are not included in this state. 353 * </ul> 354 * 355 * @param f The Fragment whose state is to be saved. 356 * @return The generated state. This will be null if there was no 357 * interesting state created by the fragment. 358 */ 359 public abstract Fragment.SavedState saveFragmentInstanceState(Fragment f); 360 361 /** 362 * Returns true if the final {@link android.app.Activity#onDestroy() Activity.onDestroy()} 363 * call has been made on the FragmentManager's Activity, so this instance is now dead. 364 */ 365 public abstract boolean isDestroyed(); 366 367 /** 368 * Registers a {@link FragmentLifecycleCallbacks} to listen to fragment lifecycle events 369 * happening in this FragmentManager. All registered callbacks will be automatically 370 * unregistered when this FragmentManager is destroyed. 371 * 372 * @param cb Callbacks to register 373 * @param recursive true to automatically register this callback for all child FragmentManagers 374 */ 375 public abstract void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb, 376 boolean recursive); 377 378 /** 379 * Unregisters a previously registered {@link FragmentLifecycleCallbacks}. If the callback 380 * was not previously registered this call has no effect. All registered callbacks will be 381 * automatically unregistered when this FragmentManager is destroyed. 382 * 383 * @param cb Callbacks to unregister 384 */ 385 public abstract void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb); 386 387 /** 388 * Print the FragmentManager's state into the given stream. 389 * 390 * @param prefix Text to print at the front of each line. 391 * @param fd The raw file descriptor that the dump is being sent to. 392 * @param writer A PrintWriter to which the dump is to be set. 393 * @param args Additional arguments to the dump request. 394 */ 395 public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args); 396 397 /** 398 * Control whether the framework's internal fragment manager debugging 399 * logs are turned on. If enabled, you will see output in logcat as 400 * the framework performs fragment operations. 401 */ 402 public static void enableDebugLogging(boolean enabled) { 403 FragmentManagerImpl.DEBUG = enabled; 404 } 405 406 /** 407 * Callback interface for listening to fragment state changes that happen 408 * within a given FragmentManager. 409 */ 410 public abstract class FragmentLifecycleCallbacks { 411 /** 412 * Called right before the fragment's {@link Fragment#onAttach(Context)} method is called. 413 * This is a good time to inject any required dependencies for the fragment before any of 414 * the fragment's lifecycle methods are invoked. 415 * 416 * @param fm Host FragmentManager 417 * @param f Fragment changing state 418 * @param context Context that the Fragment is being attached to 419 */ 420 public void onFragmentPreAttached(FragmentManager fm, Fragment f, Context context) {} 421 422 /** 423 * Called after the fragment has been attached to its host. Its host will have had 424 * <code>onAttachFragment</code> called before this call happens. 425 * 426 * @param fm Host FragmentManager 427 * @param f Fragment changing state 428 * @param context Context that the Fragment was attached to 429 */ 430 public void onFragmentAttached(FragmentManager fm, Fragment f, Context context) {} 431 432 /** 433 * Called after the fragment has returned from the FragmentManager's call to 434 * {@link Fragment#onCreate(Bundle)}. This will only happen once for any given 435 * fragment instance, though the fragment may be attached and detached multiple times. 436 * 437 * @param fm Host FragmentManager 438 * @param f Fragment changing state 439 * @param savedInstanceState Saved instance bundle from a previous instance 440 */ 441 public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {} 442 443 /** 444 * Called after the fragment has returned from the FragmentManager's call to 445 * {@link Fragment#onActivityCreated(Bundle)}. This will only happen once for any given 446 * fragment instance, though the fragment may be attached and detached multiple times. 447 * 448 * @param fm Host FragmentManager 449 * @param f Fragment changing state 450 * @param savedInstanceState Saved instance bundle from a previous instance 451 */ 452 public void onFragmentActivityCreated(FragmentManager fm, Fragment f, 453 Bundle savedInstanceState) {} 454 455 /** 456 * Called after the fragment has returned a non-null view from the FragmentManager's 457 * request to {@link Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}. 458 * 459 * @param fm Host FragmentManager 460 * @param f Fragment that created and owns the view 461 * @param v View returned by the fragment 462 * @param savedInstanceState Saved instance bundle from a previous instance 463 */ 464 public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v, 465 Bundle savedInstanceState) {} 466 467 /** 468 * Called after the fragment has returned from the FragmentManager's call to 469 * {@link Fragment#onStart()}. 470 * 471 * @param fm Host FragmentManager 472 * @param f Fragment changing state 473 */ 474 public void onFragmentStarted(FragmentManager fm, Fragment f) {} 475 476 /** 477 * Called after the fragment has returned from the FragmentManager's call to 478 * {@link Fragment#onResume()}. 479 * 480 * @param fm Host FragmentManager 481 * @param f Fragment changing state 482 */ 483 public void onFragmentResumed(FragmentManager fm, Fragment f) {} 484 485 /** 486 * Called after the fragment has returned from the FragmentManager's call to 487 * {@link Fragment#onPause()}. 488 * 489 * @param fm Host FragmentManager 490 * @param f Fragment changing state 491 */ 492 public void onFragmentPaused(FragmentManager fm, Fragment f) {} 493 494 /** 495 * Called after the fragment has returned from the FragmentManager's call to 496 * {@link Fragment#onStop()}. 497 * 498 * @param fm Host FragmentManager 499 * @param f Fragment changing state 500 */ 501 public void onFragmentStopped(FragmentManager fm, Fragment f) {} 502 503 /** 504 * Called after the fragment has returned from the FragmentManager's call to 505 * {@link Fragment#onSaveInstanceState(Bundle)}. 506 * 507 * @param fm Host FragmentManager 508 * @param f Fragment changing state 509 * @param outState Saved state bundle for the fragment 510 */ 511 public void onFragmentSaveInstanceState(FragmentManager fm, Fragment f, Bundle outState) {} 512 513 /** 514 * Called after the fragment has returned from the FragmentManager's call to 515 * {@link Fragment#onDestroyView()}. 516 * 517 * @param fm Host FragmentManager 518 * @param f Fragment changing state 519 */ 520 public void onFragmentViewDestroyed(FragmentManager fm, Fragment f) {} 521 522 /** 523 * Called after the fragment has returned from the FragmentManager's call to 524 * {@link Fragment#onDestroy()}. 525 * 526 * @param fm Host FragmentManager 527 * @param f Fragment changing state 528 */ 529 public void onFragmentDestroyed(FragmentManager fm, Fragment f) {} 530 531 /** 532 * Called after the fragment has returned from the FragmentManager's call to 533 * {@link Fragment#onDetach()}. 534 * 535 * @param fm Host FragmentManager 536 * @param f Fragment changing state 537 */ 538 public void onFragmentDetached(FragmentManager fm, Fragment f) {} 539 } 540} 541 542final class FragmentManagerState implements Parcelable { 543 FragmentState[] mActive; 544 int[] mAdded; 545 BackStackState[] mBackStack; 546 547 public FragmentManagerState() { 548 } 549 550 public FragmentManagerState(Parcel in) { 551 mActive = in.createTypedArray(FragmentState.CREATOR); 552 mAdded = in.createIntArray(); 553 mBackStack = in.createTypedArray(BackStackState.CREATOR); 554 } 555 556 @Override 557 public int describeContents() { 558 return 0; 559 } 560 561 @Override 562 public void writeToParcel(Parcel dest, int flags) { 563 dest.writeTypedArray(mActive, flags); 564 dest.writeIntArray(mAdded); 565 dest.writeTypedArray(mBackStack, flags); 566 } 567 568 public static final Parcelable.Creator<FragmentManagerState> CREATOR 569 = new Parcelable.Creator<FragmentManagerState>() { 570 @Override 571 public FragmentManagerState createFromParcel(Parcel in) { 572 return new FragmentManagerState(in); 573 } 574 575 @Override 576 public FragmentManagerState[] newArray(int size) { 577 return new FragmentManagerState[size]; 578 } 579 }; 580} 581 582/** 583 * Container for fragments associated with an activity. 584 */ 585final class FragmentManagerImpl extends FragmentManager implements LayoutInflaterFactory { 586 static boolean DEBUG = false; 587 static final String TAG = "FragmentManager"; 588 589 static final boolean HONEYCOMB = android.os.Build.VERSION.SDK_INT >= 11; 590 591 static final String TARGET_REQUEST_CODE_STATE_TAG = "android:target_req_state"; 592 static final String TARGET_STATE_TAG = "android:target_state"; 593 static final String VIEW_STATE_TAG = "android:view_state"; 594 static final String USER_VISIBLE_HINT_TAG = "android:user_visible_hint"; 595 596 static class AnimateOnHWLayerIfNeededListener implements AnimationListener { 597 private AnimationListener mOriginalListener; 598 private boolean mShouldRunOnHWLayer; 599 View mView; 600 601 public AnimateOnHWLayerIfNeededListener(final View v, Animation anim) { 602 if (v == null || anim == null) { 603 return; 604 } 605 mView = v; 606 } 607 608 public AnimateOnHWLayerIfNeededListener(final View v, Animation anim, 609 AnimationListener listener) { 610 if (v == null || anim == null) { 611 return; 612 } 613 mOriginalListener = listener; 614 mView = v; 615 mShouldRunOnHWLayer = true; 616 } 617 618 @Override 619 @CallSuper 620 public void onAnimationStart(Animation animation) { 621 if (mOriginalListener != null) { 622 mOriginalListener.onAnimationStart(animation); 623 } 624 } 625 626 @Override 627 @CallSuper 628 public void onAnimationEnd(Animation animation) { 629 if (mView != null && mShouldRunOnHWLayer) { 630 // If we're attached to a window, assume we're in the normal performTraversals 631 // drawing path for Animations running. It's not safe to change the layer type 632 // during drawing, so post it to the View to run later. If we're not attached 633 // or we're running on N and above, post it to the view. If we're not on N and 634 // not attached, do it right now since existing platform versions don't run the 635 // hwui renderer for detached views off the UI thread making changing layer type 636 // safe, but posting may not be. 637 // Prior to N posting to a detached view from a non-Looper thread could cause 638 // leaks, since the thread-local run queue on a non-Looper thread would never 639 // be flushed. 640 if (ViewCompat.isAttachedToWindow(mView) || BuildCompat.isAtLeastN()) { 641 mView.post(new Runnable() { 642 @Override 643 public void run() { 644 ViewCompat.setLayerType(mView, ViewCompat.LAYER_TYPE_NONE, null); 645 } 646 }); 647 } else { 648 ViewCompat.setLayerType(mView, ViewCompat.LAYER_TYPE_NONE, null); 649 } 650 } 651 if (mOriginalListener != null) { 652 mOriginalListener.onAnimationEnd(animation); 653 } 654 } 655 656 @Override 657 public void onAnimationRepeat(Animation animation) { 658 if (mOriginalListener != null) { 659 mOriginalListener.onAnimationRepeat(animation); 660 } 661 } 662 } 663 664 ArrayList<OpGenerator> mPendingActions; 665 Runnable[] mTmpActions; 666 boolean mExecutingActions; 667 668 ArrayList<Fragment> mActive; 669 ArrayList<Fragment> mAdded; 670 ArrayList<Integer> mAvailIndices; 671 ArrayList<BackStackRecord> mBackStack; 672 ArrayList<Fragment> mCreatedMenus; 673 674 // Must be accessed while locked. 675 ArrayList<BackStackRecord> mBackStackIndices; 676 ArrayList<Integer> mAvailBackStackIndices; 677 678 ArrayList<OnBackStackChangedListener> mBackStackChangeListeners; 679 private CopyOnWriteArrayList<Pair<FragmentLifecycleCallbacks, Boolean>> mLifecycleCallbacks; 680 681 int mCurState = Fragment.INITIALIZING; 682 FragmentHostCallback mHost; 683 FragmentContainer mContainer; 684 Fragment mParent; 685 686 static Field sAnimationListenerField = null; 687 688 boolean mNeedMenuInvalidate; 689 boolean mStateSaved; 690 boolean mDestroyed; 691 String mNoTransactionsBecause; 692 boolean mHavePendingDeferredStart; 693 694 // Temporary vars for optimizing execution of BackStackRecords: 695 ArrayList<BackStackRecord> mTmpRecords; 696 ArrayList<Boolean> mTmpIsPop; 697 ArrayList<Fragment> mTmpAddedFragments; 698 699 // Temporary vars for state save and restore. 700 Bundle mStateBundle = null; 701 SparseArray<Parcelable> mStateArray = null; 702 703 // Postponed transactions. 704 ArrayList<StartEnterTransitionListener> mPostponedTransactions; 705 706 Runnable mExecCommit = new Runnable() { 707 @Override 708 public void run() { 709 execPendingActions(); 710 } 711 }; 712 713 static boolean modifiesAlpha(Animation anim) { 714 if (anim instanceof AlphaAnimation) { 715 return true; 716 } else if (anim instanceof AnimationSet) { 717 List<Animation> anims = ((AnimationSet) anim).getAnimations(); 718 for (int i = 0; i < anims.size(); i++) { 719 if (anims.get(i) instanceof AlphaAnimation) { 720 return true; 721 } 722 } 723 } 724 return false; 725 } 726 727 static boolean shouldRunOnHWLayer(View v, Animation anim) { 728 return Build.VERSION.SDK_INT >= 19 729 && ViewCompat.getLayerType(v) == ViewCompat.LAYER_TYPE_NONE 730 && ViewCompat.hasOverlappingRendering(v) 731 && modifiesAlpha(anim); 732 } 733 734 private void throwException(RuntimeException ex) { 735 Log.e(TAG, ex.getMessage()); 736 Log.e(TAG, "Activity state:"); 737 LogWriter logw = new LogWriter(TAG); 738 PrintWriter pw = new PrintWriter(logw); 739 if (mHost != null) { 740 try { 741 mHost.onDump(" ", null, pw, new String[] { }); 742 } catch (Exception e) { 743 Log.e(TAG, "Failed dumping state", e); 744 } 745 } else { 746 try { 747 dump(" ", null, pw, new String[] { }); 748 } catch (Exception e) { 749 Log.e(TAG, "Failed dumping state", e); 750 } 751 } 752 throw ex; 753 } 754 755 @Override 756 public FragmentTransaction beginTransaction() { 757 return new BackStackRecord(this); 758 } 759 760 @Override 761 public boolean executePendingTransactions() { 762 boolean updates = execPendingActions(); 763 forcePostponedTransactions(); 764 return updates; 765 } 766 767 @Override 768 public void popBackStack() { 769 enqueueAction(new PopBackStackState(null, -1, 0), false); 770 } 771 772 @Override 773 public boolean popBackStackImmediate() { 774 checkStateLoss(); 775 return popBackStackImmediate(null, -1, 0); 776 } 777 778 @Override 779 public void popBackStack(final String name, final int flags) { 780 enqueueAction(new PopBackStackState(name, -1, flags), false); 781 } 782 783 @Override 784 public boolean popBackStackImmediate(String name, int flags) { 785 checkStateLoss(); 786 return popBackStackImmediate(name, -1, flags); 787 } 788 789 @Override 790 public void popBackStack(final int id, final int flags) { 791 if (id < 0) { 792 throw new IllegalArgumentException("Bad id: " + id); 793 } 794 enqueueAction(new PopBackStackState(null, id, flags), false); 795 } 796 797 @Override 798 public boolean popBackStackImmediate(int id, int flags) { 799 checkStateLoss(); 800 execPendingActions(); 801 if (id < 0) { 802 throw new IllegalArgumentException("Bad id: " + id); 803 } 804 return popBackStackImmediate(null, id, flags); 805 } 806 807 /** 808 * Used by all public popBackStackImmediate methods, this executes pending transactions and 809 * returns true if the pop action did anything, regardless of what other pending 810 * transactions did. 811 * 812 * @return true if the pop operation did anything or false otherwise. 813 */ 814 private boolean popBackStackImmediate(String name, int id, int flags) { 815 execPendingActions(); 816 ensureExecReady(true); 817 818 boolean executePop = popBackStackState(mTmpRecords, mTmpIsPop, name, id, flags); 819 if (executePop) { 820 mExecutingActions = true; 821 try { 822 optimizeAndExecuteOps(mTmpRecords, mTmpIsPop); 823 } finally { 824 cleanupExec(); 825 } 826 } 827 828 doPendingDeferredStart(); 829 return executePop; 830 } 831 832 @Override 833 public int getBackStackEntryCount() { 834 return mBackStack != null ? mBackStack.size() : 0; 835 } 836 837 @Override 838 public BackStackEntry getBackStackEntryAt(int index) { 839 return mBackStack.get(index); 840 } 841 842 @Override 843 public void addOnBackStackChangedListener(OnBackStackChangedListener listener) { 844 if (mBackStackChangeListeners == null) { 845 mBackStackChangeListeners = new ArrayList<OnBackStackChangedListener>(); 846 } 847 mBackStackChangeListeners.add(listener); 848 } 849 850 @Override 851 public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) { 852 if (mBackStackChangeListeners != null) { 853 mBackStackChangeListeners.remove(listener); 854 } 855 } 856 857 @Override 858 public void putFragment(Bundle bundle, String key, Fragment fragment) { 859 if (fragment.mIndex < 0) { 860 throwException(new IllegalStateException("Fragment " + fragment 861 + " is not currently in the FragmentManager")); 862 } 863 bundle.putInt(key, fragment.mIndex); 864 } 865 866 @Override 867 public Fragment getFragment(Bundle bundle, String key) { 868 int index = bundle.getInt(key, -1); 869 if (index == -1) { 870 return null; 871 } 872 if (index >= mActive.size()) { 873 throwException(new IllegalStateException("Fragment no longer exists for key " 874 + key + ": index " + index)); 875 } 876 Fragment f = mActive.get(index); 877 if (f == null) { 878 throwException(new IllegalStateException("Fragment no longer exists for key " 879 + key + ": index " + index)); 880 } 881 return f; 882 } 883 884 @Override 885 public List<Fragment> getFragments() { 886 return mActive; 887 } 888 889 @Override 890 public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) { 891 if (fragment.mIndex < 0) { 892 throwException( new IllegalStateException("Fragment " + fragment 893 + " is not currently in the FragmentManager")); 894 } 895 if (fragment.mState > Fragment.INITIALIZING) { 896 Bundle result = saveFragmentBasicState(fragment); 897 return result != null ? new Fragment.SavedState(result) : null; 898 } 899 return null; 900 } 901 902 @Override 903 public boolean isDestroyed() { 904 return mDestroyed; 905 } 906 907 @Override 908 public String toString() { 909 StringBuilder sb = new StringBuilder(128); 910 sb.append("FragmentManager{"); 911 sb.append(Integer.toHexString(System.identityHashCode(this))); 912 sb.append(" in "); 913 if (mParent != null) { 914 DebugUtils.buildShortClassTag(mParent, sb); 915 } else { 916 DebugUtils.buildShortClassTag(mHost, sb); 917 } 918 sb.append("}}"); 919 return sb.toString(); 920 } 921 922 @Override 923 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 924 String innerPrefix = prefix + " "; 925 926 int N; 927 if (mActive != null) { 928 N = mActive.size(); 929 if (N > 0) { 930 writer.print(prefix); writer.print("Active Fragments in "); 931 writer.print(Integer.toHexString(System.identityHashCode(this))); 932 writer.println(":"); 933 for (int i=0; i<N; i++) { 934 Fragment f = mActive.get(i); 935 writer.print(prefix); writer.print(" #"); writer.print(i); 936 writer.print(": "); writer.println(f); 937 if (f != null) { 938 f.dump(innerPrefix, fd, writer, args); 939 } 940 } 941 } 942 } 943 944 if (mAdded != null) { 945 N = mAdded.size(); 946 if (N > 0) { 947 writer.print(prefix); writer.println("Added Fragments:"); 948 for (int i=0; i<N; i++) { 949 Fragment f = mAdded.get(i); 950 writer.print(prefix); writer.print(" #"); writer.print(i); 951 writer.print(": "); writer.println(f.toString()); 952 } 953 } 954 } 955 956 if (mCreatedMenus != null) { 957 N = mCreatedMenus.size(); 958 if (N > 0) { 959 writer.print(prefix); writer.println("Fragments Created Menus:"); 960 for (int i=0; i<N; i++) { 961 Fragment f = mCreatedMenus.get(i); 962 writer.print(prefix); writer.print(" #"); writer.print(i); 963 writer.print(": "); writer.println(f.toString()); 964 } 965 } 966 } 967 968 if (mBackStack != null) { 969 N = mBackStack.size(); 970 if (N > 0) { 971 writer.print(prefix); writer.println("Back Stack:"); 972 for (int i=0; i<N; i++) { 973 BackStackRecord bs = mBackStack.get(i); 974 writer.print(prefix); writer.print(" #"); writer.print(i); 975 writer.print(": "); writer.println(bs.toString()); 976 bs.dump(innerPrefix, fd, writer, args); 977 } 978 } 979 } 980 981 synchronized (this) { 982 if (mBackStackIndices != null) { 983 N = mBackStackIndices.size(); 984 if (N > 0) { 985 writer.print(prefix); writer.println("Back Stack Indices:"); 986 for (int i=0; i<N; i++) { 987 BackStackRecord bs = mBackStackIndices.get(i); 988 writer.print(prefix); writer.print(" #"); writer.print(i); 989 writer.print(": "); writer.println(bs); 990 } 991 } 992 } 993 994 if (mAvailBackStackIndices != null && mAvailBackStackIndices.size() > 0) { 995 writer.print(prefix); writer.print("mAvailBackStackIndices: "); 996 writer.println(Arrays.toString(mAvailBackStackIndices.toArray())); 997 } 998 } 999 1000 if (mPendingActions != null) { 1001 N = mPendingActions.size(); 1002 if (N > 0) { 1003 writer.print(prefix); writer.println("Pending Actions:"); 1004 for (int i=0; i<N; i++) { 1005 OpGenerator r = mPendingActions.get(i); 1006 writer.print(prefix); writer.print(" #"); writer.print(i); 1007 writer.print(": "); writer.println(r); 1008 } 1009 } 1010 } 1011 1012 writer.print(prefix); writer.println("FragmentManager misc state:"); 1013 writer.print(prefix); writer.print(" mHost="); writer.println(mHost); 1014 writer.print(prefix); writer.print(" mContainer="); writer.println(mContainer); 1015 if (mParent != null) { 1016 writer.print(prefix); writer.print(" mParent="); writer.println(mParent); 1017 } 1018 writer.print(prefix); writer.print(" mCurState="); writer.print(mCurState); 1019 writer.print(" mStateSaved="); writer.print(mStateSaved); 1020 writer.print(" mDestroyed="); writer.println(mDestroyed); 1021 if (mNeedMenuInvalidate) { 1022 writer.print(prefix); writer.print(" mNeedMenuInvalidate="); 1023 writer.println(mNeedMenuInvalidate); 1024 } 1025 if (mNoTransactionsBecause != null) { 1026 writer.print(prefix); writer.print(" mNoTransactionsBecause="); 1027 writer.println(mNoTransactionsBecause); 1028 } 1029 if (mAvailIndices != null && mAvailIndices.size() > 0) { 1030 writer.print(prefix); writer.print(" mAvailIndices: "); 1031 writer.println(Arrays.toString(mAvailIndices.toArray())); 1032 } 1033 } 1034 1035 static final Interpolator DECELERATE_QUINT = new DecelerateInterpolator(2.5f); 1036 static final Interpolator DECELERATE_CUBIC = new DecelerateInterpolator(1.5f); 1037 static final Interpolator ACCELERATE_QUINT = new AccelerateInterpolator(2.5f); 1038 static final Interpolator ACCELERATE_CUBIC = new AccelerateInterpolator(1.5f); 1039 1040 static final int ANIM_DUR = 220; 1041 1042 static Animation makeOpenCloseAnimation(Context context, float startScale, 1043 float endScale, float startAlpha, float endAlpha) { 1044 AnimationSet set = new AnimationSet(false); 1045 ScaleAnimation scale = new ScaleAnimation(startScale, endScale, startScale, endScale, 1046 Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f); 1047 scale.setInterpolator(DECELERATE_QUINT); 1048 scale.setDuration(ANIM_DUR); 1049 set.addAnimation(scale); 1050 AlphaAnimation alpha = new AlphaAnimation(startAlpha, endAlpha); 1051 alpha.setInterpolator(DECELERATE_CUBIC); 1052 alpha.setDuration(ANIM_DUR); 1053 set.addAnimation(alpha); 1054 return set; 1055 } 1056 1057 static Animation makeFadeAnimation(Context context, float start, float end) { 1058 AlphaAnimation anim = new AlphaAnimation(start, end); 1059 anim.setInterpolator(DECELERATE_CUBIC); 1060 anim.setDuration(ANIM_DUR); 1061 return anim; 1062 } 1063 1064 Animation loadAnimation(Fragment fragment, int transit, boolean enter, 1065 int transitionStyle) { 1066 Animation animObj = fragment.onCreateAnimation(transit, enter, fragment.getNextAnim()); 1067 if (animObj != null) { 1068 return animObj; 1069 } 1070 1071 if (fragment.getNextAnim() != 0) { 1072 Animation anim = AnimationUtils.loadAnimation(mHost.getContext(), 1073 fragment.getNextAnim()); 1074 if (anim != null) { 1075 return anim; 1076 } 1077 } 1078 1079 if (transit == 0) { 1080 return null; 1081 } 1082 1083 int styleIndex = transitToStyleIndex(transit, enter); 1084 if (styleIndex < 0) { 1085 return null; 1086 } 1087 1088 switch (styleIndex) { 1089 case ANIM_STYLE_OPEN_ENTER: 1090 return makeOpenCloseAnimation(mHost.getContext(), 1.125f, 1.0f, 0, 1); 1091 case ANIM_STYLE_OPEN_EXIT: 1092 return makeOpenCloseAnimation(mHost.getContext(), 1.0f, .975f, 1, 0); 1093 case ANIM_STYLE_CLOSE_ENTER: 1094 return makeOpenCloseAnimation(mHost.getContext(), .975f, 1.0f, 0, 1); 1095 case ANIM_STYLE_CLOSE_EXIT: 1096 return makeOpenCloseAnimation(mHost.getContext(), 1.0f, 1.075f, 1, 0); 1097 case ANIM_STYLE_FADE_ENTER: 1098 return makeFadeAnimation(mHost.getContext(), 0, 1); 1099 case ANIM_STYLE_FADE_EXIT: 1100 return makeFadeAnimation(mHost.getContext(), 1, 0); 1101 } 1102 1103 if (transitionStyle == 0 && mHost.onHasWindowAnimations()) { 1104 transitionStyle = mHost.onGetWindowAnimations(); 1105 } 1106 if (transitionStyle == 0) { 1107 return null; 1108 } 1109 1110 //TypedArray attrs = mActivity.obtainStyledAttributes(transitionStyle, 1111 // com.android.internal.R.styleable.FragmentAnimation); 1112 //int anim = attrs.getResourceId(styleIndex, 0); 1113 //attrs.recycle(); 1114 1115 //if (anim == 0) { 1116 // return null; 1117 //} 1118 1119 //return AnimatorInflater.loadAnimator(mActivity, anim); 1120 return null; 1121 } 1122 1123 public void performPendingDeferredStart(Fragment f) { 1124 if (f.mDeferStart) { 1125 if (mExecutingActions) { 1126 // Wait until we're done executing our pending transactions 1127 mHavePendingDeferredStart = true; 1128 return; 1129 } 1130 f.mDeferStart = false; 1131 moveToState(f, mCurState, 0, 0, false); 1132 } 1133 } 1134 1135 /** 1136 * Sets the to be animated view on hardware layer during the animation. Note 1137 * that calling this will replace any existing animation listener on the animation 1138 * with a new one, as animations do not support more than one listeners. Therefore, 1139 * animations that already have listeners should do the layer change operations 1140 * in their existing listeners, rather than calling this function. 1141 */ 1142 private void setHWLayerAnimListenerIfAlpha(final View v, Animation anim) { 1143 if (v == null || anim == null) { 1144 return; 1145 } 1146 if (shouldRunOnHWLayer(v, anim)) { 1147 AnimationListener originalListener = null; 1148 try { 1149 if (sAnimationListenerField == null) { 1150 sAnimationListenerField = Animation.class.getDeclaredField("mListener"); 1151 sAnimationListenerField.setAccessible(true); 1152 } 1153 originalListener = (AnimationListener) sAnimationListenerField.get(anim); 1154 } catch (NoSuchFieldException e) { 1155 Log.e(TAG, "No field with the name mListener is found in Animation class", e); 1156 } catch (IllegalAccessException e) { 1157 Log.e(TAG, "Cannot access Animation's mListener field", e); 1158 } 1159 // If there's already a listener set on the animation, we need wrap the new listener 1160 // around the existing listener, so that they will both get animation listener 1161 // callbacks. 1162 ViewCompat.setLayerType(v, ViewCompat.LAYER_TYPE_HARDWARE, null); 1163 anim.setAnimationListener(new AnimateOnHWLayerIfNeededListener(v, anim, 1164 originalListener)); 1165 } 1166 } 1167 1168 boolean isStateAtLeast(int state) { 1169 return mCurState >= state; 1170 } 1171 1172 void moveToState(Fragment f, int newState, int transit, int transitionStyle, 1173 boolean keepActive) { 1174 // Fragments that are not currently added will sit in the onCreate() state. 1175 if ((!f.mAdded || f.mDetached) && newState > Fragment.CREATED) { 1176 newState = Fragment.CREATED; 1177 } 1178 if (f.mRemoving && newState > f.mState) { 1179 // While removing a fragment, we can't change it to a higher state. 1180 newState = f.mState; 1181 } 1182 // Defer start if requested; don't allow it to move to STARTED or higher 1183 // if it's not already started. 1184 if (f.mDeferStart && f.mState < Fragment.STARTED && newState > Fragment.STOPPED) { 1185 newState = Fragment.STOPPED; 1186 } 1187 if (f.mState < newState) { 1188 // For fragments that are created from a layout, when restoring from 1189 // state we don't want to allow them to be created until they are 1190 // being reloaded from the layout. 1191 if (f.mFromLayout && !f.mInLayout) { 1192 return; 1193 } 1194 if (f.getAnimatingAway() != null) { 1195 // The fragment is currently being animated... but! Now we 1196 // want to move our state back up. Give up on waiting for the 1197 // animation, move to whatever the final state should be once 1198 // the animation is done, and then we can proceed from there. 1199 f.setAnimatingAway(null); 1200 moveToState(f, f.getStateAfterAnimating(), 0, 0, true); 1201 } 1202 switch (f.mState) { 1203 case Fragment.INITIALIZING: 1204 if (DEBUG) Log.v(TAG, "moveto CREATED: " + f); 1205 if (f.mSavedFragmentState != null) { 1206 f.mSavedFragmentState.setClassLoader(mHost.getContext().getClassLoader()); 1207 f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray( 1208 FragmentManagerImpl.VIEW_STATE_TAG); 1209 f.mTarget = getFragment(f.mSavedFragmentState, 1210 FragmentManagerImpl.TARGET_STATE_TAG); 1211 if (f.mTarget != null) { 1212 f.mTargetRequestCode = f.mSavedFragmentState.getInt( 1213 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0); 1214 } 1215 f.mUserVisibleHint = f.mSavedFragmentState.getBoolean( 1216 FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true); 1217 if (!f.mUserVisibleHint) { 1218 f.mDeferStart = true; 1219 if (newState > Fragment.STOPPED) { 1220 newState = Fragment.STOPPED; 1221 } 1222 } 1223 } 1224 f.mHost = mHost; 1225 f.mParentFragment = mParent; 1226 f.mFragmentManager = mParent != null 1227 ? mParent.mChildFragmentManager : mHost.getFragmentManagerImpl(); 1228 dispatchOnFragmentPreAttached(f, mHost.getContext(), false); 1229 f.mCalled = false; 1230 f.onAttach(mHost.getContext()); 1231 if (!f.mCalled) { 1232 throw new SuperNotCalledException("Fragment " + f 1233 + " did not call through to super.onAttach()"); 1234 } 1235 if (f.mParentFragment == null) { 1236 mHost.onAttachFragment(f); 1237 } else { 1238 f.mParentFragment.onAttachFragment(f); 1239 } 1240 dispatchOnFragmentAttached(f, mHost.getContext(), false); 1241 1242 if (!f.mRetaining) { 1243 f.performCreate(f.mSavedFragmentState); 1244 dispatchOnFragmentCreated(f, f.mSavedFragmentState, false); 1245 } else { 1246 f.restoreChildFragmentState(f.mSavedFragmentState); 1247 f.mState = Fragment.CREATED; 1248 } 1249 f.mRetaining = false; 1250 if (f.mFromLayout) { 1251 // For fragments that are part of the content view 1252 // layout, we need to instantiate the view immediately 1253 // and the inflater will take care of adding it. 1254 f.mView = f.performCreateView(f.getLayoutInflater( 1255 f.mSavedFragmentState), null, f.mSavedFragmentState); 1256 if (f.mView != null) { 1257 f.mInnerView = f.mView; 1258 if (Build.VERSION.SDK_INT >= 11) { 1259 ViewCompat.setSaveFromParentEnabled(f.mView, false); 1260 } else { 1261 f.mView = NoSaveStateFrameLayout.wrap(f.mView); 1262 } 1263 if (f.mHidden) f.mView.setVisibility(View.GONE); 1264 f.onViewCreated(f.mView, f.mSavedFragmentState); 1265 dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, false); 1266 } else { 1267 f.mInnerView = null; 1268 } 1269 } 1270 case Fragment.CREATED: 1271 if (newState > Fragment.CREATED) { 1272 if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f); 1273 if (!f.mFromLayout) { 1274 ViewGroup container = null; 1275 if (f.mContainerId != 0) { 1276 if (f.mContainerId == View.NO_ID) { 1277 throwException(new IllegalArgumentException( 1278 "Cannot create fragment " 1279 + f 1280 + " for a container view with no id")); 1281 } 1282 container = (ViewGroup) mContainer.onFindViewById(f.mContainerId); 1283 if (container == null && !f.mRestored) { 1284 String resName; 1285 try { 1286 resName = f.getResources().getResourceName(f.mContainerId); 1287 } catch (NotFoundException e) { 1288 resName = "unknown"; 1289 } 1290 throwException(new IllegalArgumentException( 1291 "No view found for id 0x" 1292 + Integer.toHexString(f.mContainerId) + " (" 1293 + resName 1294 + ") for fragment " + f)); 1295 } 1296 } 1297 f.mContainer = container; 1298 f.mView = f.performCreateView(f.getLayoutInflater( 1299 f.mSavedFragmentState), container, f.mSavedFragmentState); 1300 if (f.mView != null) { 1301 f.mInnerView = f.mView; 1302 if (Build.VERSION.SDK_INT >= 11) { 1303 ViewCompat.setSaveFromParentEnabled(f.mView, false); 1304 } else { 1305 f.mView = NoSaveStateFrameLayout.wrap(f.mView); 1306 } 1307 if (container != null) { 1308 container.addView(f.mView); 1309 } 1310 if (f.mHidden) { 1311 f.mView.setVisibility(View.GONE); 1312 } 1313 f.onViewCreated(f.mView, f.mSavedFragmentState); 1314 dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, 1315 false); 1316 // Only animate the view if it is visible. This is done after 1317 // dispatchOnFragmentViewCreated in case visibility is changed 1318 f.mIsNewlyAdded = (f.mView.getVisibility() == View.VISIBLE) 1319 && f.mContainer != null; 1320 } else { 1321 f.mInnerView = null; 1322 } 1323 } 1324 1325 f.performActivityCreated(f.mSavedFragmentState); 1326 dispatchOnFragmentActivityCreated(f, f.mSavedFragmentState, false); 1327 if (f.mView != null) { 1328 f.restoreViewState(f.mSavedFragmentState); 1329 } 1330 f.mSavedFragmentState = null; 1331 } 1332 case Fragment.ACTIVITY_CREATED: 1333 if (newState > Fragment.ACTIVITY_CREATED) { 1334 f.mState = Fragment.STOPPED; 1335 } 1336 case Fragment.STOPPED: 1337 if (newState > Fragment.STOPPED) { 1338 if (DEBUG) Log.v(TAG, "moveto STARTED: " + f); 1339 f.performStart(); 1340 dispatchOnFragmentStarted(f, false); 1341 } 1342 case Fragment.STARTED: 1343 if (newState > Fragment.STARTED) { 1344 if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f); 1345 f.performResume(); 1346 dispatchOnFragmentResumed(f, false); 1347 f.mSavedFragmentState = null; 1348 f.mSavedViewState = null; 1349 } 1350 } 1351 } else if (f.mState > newState) { 1352 switch (f.mState) { 1353 case Fragment.RESUMED: 1354 if (newState < Fragment.RESUMED) { 1355 if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f); 1356 f.performPause(); 1357 dispatchOnFragmentPaused(f, false); 1358 } 1359 case Fragment.STARTED: 1360 if (newState < Fragment.STARTED) { 1361 if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f); 1362 f.performStop(); 1363 dispatchOnFragmentStopped(f, false); 1364 } 1365 case Fragment.STOPPED: 1366 if (newState < Fragment.STOPPED) { 1367 if (DEBUG) Log.v(TAG, "movefrom STOPPED: " + f); 1368 f.performReallyStop(); 1369 } 1370 case Fragment.ACTIVITY_CREATED: 1371 if (newState < Fragment.ACTIVITY_CREATED) { 1372 if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f); 1373 if (f.mView != null) { 1374 // Need to save the current view state if not 1375 // done already. 1376 if (mHost.onShouldSaveFragmentState(f) && f.mSavedViewState == null) { 1377 saveFragmentViewState(f); 1378 } 1379 } 1380 f.performDestroyView(); 1381 dispatchOnFragmentViewDestroyed(f, false); 1382 if (f.mView != null && f.mContainer != null) { 1383 Animation anim = null; 1384 if (mCurState > Fragment.INITIALIZING && !mDestroyed 1385 && f.mView.getVisibility() == View.VISIBLE) { 1386 anim = loadAnimation(f, transit, false, 1387 transitionStyle); 1388 } 1389 if (anim != null) { 1390 final Fragment fragment = f; 1391 f.setAnimatingAway(f.mView); 1392 f.setStateAfterAnimating(newState); 1393 final View viewToAnimate = f.mView; 1394 anim.setAnimationListener(new AnimateOnHWLayerIfNeededListener( 1395 viewToAnimate, anim) { 1396 @Override 1397 public void onAnimationEnd(Animation animation) { 1398 super.onAnimationEnd(animation); 1399 if (fragment.getAnimatingAway() != null) { 1400 fragment.setAnimatingAway(null); 1401 moveToState(fragment, fragment.getStateAfterAnimating(), 1402 0, 0, false); 1403 } 1404 } 1405 }); 1406 f.mView.startAnimation(anim); 1407 } 1408 f.mContainer.removeView(f.mView); 1409 } 1410 f.mContainer = null; 1411 f.mView = null; 1412 f.mInnerView = null; 1413 } 1414 case Fragment.CREATED: 1415 if (newState < Fragment.CREATED) { 1416 if (mDestroyed) { 1417 if (f.getAnimatingAway() != null) { 1418 // The fragment's containing activity is 1419 // being destroyed, but this fragment is 1420 // currently animating away. Stop the 1421 // animation right now -- it is not needed, 1422 // and we can't wait any more on destroying 1423 // the fragment. 1424 View v = f.getAnimatingAway(); 1425 f.setAnimatingAway(null); 1426 v.clearAnimation(); 1427 } 1428 } 1429 if (f.getAnimatingAway() != null) { 1430 // We are waiting for the fragment's view to finish 1431 // animating away. Just make a note of the state 1432 // the fragment now should move to once the animation 1433 // is done. 1434 f.setStateAfterAnimating(newState); 1435 newState = Fragment.CREATED; 1436 } else { 1437 if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f); 1438 if (!f.mRetaining) { 1439 f.performDestroy(); 1440 dispatchOnFragmentDestroyed(f, false); 1441 } else { 1442 f.mState = Fragment.INITIALIZING; 1443 } 1444 1445 f.performDetach(); 1446 dispatchOnFragmentDetached(f, false); 1447 if (!keepActive) { 1448 if (!f.mRetaining) { 1449 makeInactive(f); 1450 } else { 1451 f.mHost = null; 1452 f.mParentFragment = null; 1453 f.mFragmentManager = null; 1454 } 1455 } 1456 } 1457 } 1458 } 1459 } 1460 1461 if (f.mState != newState) { 1462 Log.w(TAG, "moveToState: Fragment state for " + f + " not updated inline; " 1463 + "expected state " + newState + " found " + f.mState); 1464 f.mState = newState; 1465 } 1466 } 1467 1468 void moveToState(Fragment f) { 1469 moveToState(f, mCurState, 0, 0, false); 1470 } 1471 1472 /** 1473 * Fragments that have been shown or hidden don't have their visibility changed or 1474 * animations run during the {@link #showFragment(Fragment)} or {@link #hideFragment(Fragment)} 1475 * calls. After fragments are brought to their final state in 1476 * {@link #moveFragmentToExpectedState(Fragment)} the fragments that have been shown or 1477 * hidden must have their visibility changed and their animations started here. 1478 * 1479 * @param fragment The fragment with mHiddenChanged = true that should change its View's 1480 * visibility and start the show or hide animation. 1481 */ 1482 void completeShowHideFragment(final Fragment fragment) { 1483 if (fragment.mView != null) { 1484 Animation anim = loadAnimation(fragment, fragment.getNextTransition(), 1485 !fragment.mHidden, fragment.getNextTransitionStyle()); 1486 if (anim != null) { 1487 setHWLayerAnimListenerIfAlpha(fragment.mView, anim); 1488 fragment.mView.startAnimation(anim); 1489 setHWLayerAnimListenerIfAlpha(fragment.mView, anim); 1490 anim.start(); 1491 } 1492 final int visibility = fragment.mHidden && !fragment.isHideReplaced() 1493 ? View.GONE 1494 : View.VISIBLE; 1495 fragment.mView.setVisibility(visibility); 1496 if (fragment.isHideReplaced()) { 1497 fragment.setHideReplaced(false); 1498 } 1499 } 1500 if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) { 1501 mNeedMenuInvalidate = true; 1502 } 1503 fragment.mHiddenChanged = false; 1504 fragment.onHiddenChanged(fragment.mHidden); 1505 } 1506 1507 /** 1508 * Moves a fragment to its expected final state or the fragment manager's state, depending 1509 * on whether the fragment manager's state is raised properly. 1510 * 1511 * @param f The fragment to change. 1512 */ 1513 void moveFragmentToExpectedState(Fragment f) { 1514 if (f == null) { 1515 return; 1516 } 1517 int nextState = mCurState; 1518 if (f.mRemoving) { 1519 if (f.isInBackStack()) { 1520 nextState = Math.min(nextState, Fragment.CREATED); 1521 } else { 1522 nextState = Math.min(nextState, Fragment.INITIALIZING); 1523 } 1524 } 1525 moveToState(f, nextState, f.getNextTransition(), f.getNextTransitionStyle(), false); 1526 1527 if (f.mView != null) { 1528 // Move the view if it is out of order 1529 Fragment underFragment = findFragmentUnder(f); 1530 if (underFragment != null) { 1531 final View underView = underFragment.mView; 1532 // make sure this fragment is in the right order. 1533 final ViewGroup container = f.mContainer; 1534 int underIndex = container.indexOfChild(underView); 1535 int viewIndex = container.indexOfChild(f.mView); 1536 if (viewIndex < underIndex) { 1537 container.removeViewAt(viewIndex); 1538 container.addView(f.mView, underIndex); 1539 } 1540 } 1541 if (f.mIsNewlyAdded && f.mContainer != null) { 1542 // Make it visible and run the animations 1543 f.mView.setVisibility(View.VISIBLE); 1544 f.mIsNewlyAdded = false; 1545 // run animations: 1546 Animation anim = loadAnimation(f, f.getNextTransition(), true, 1547 f.getNextTransitionStyle()); 1548 if (anim != null) { 1549 setHWLayerAnimListenerIfAlpha(f.mView, anim); 1550 f.mView.startAnimation(anim); 1551 } 1552 } 1553 } 1554 if (f.mHiddenChanged) { 1555 completeShowHideFragment(f); 1556 } 1557 } 1558 1559 /** 1560 * Changes the state of the fragment manager to {@code newState}. If the fragment manager 1561 * changes state or {@code always} is {@code true}, any fragments within it have their 1562 * states updated as well. 1563 * 1564 * @param newState The new state for the fragment manager 1565 * @param always If {@code true}, all fragments update their state, even 1566 * if {@code newState} matches the current fragment manager's state. 1567 */ 1568 void moveToState(int newState, boolean always) { 1569 if (mHost == null && newState != Fragment.INITIALIZING) { 1570 throw new IllegalStateException("No activity"); 1571 } 1572 1573 if (!always && newState == mCurState) { 1574 return; 1575 } 1576 1577 mCurState = newState; 1578 1579 if (mActive != null) { 1580 boolean loadersRunning = false; 1581 1582 // Must add them in the proper order. mActive fragments may be out of order 1583 if (mAdded != null) { 1584 final int numAdded = mAdded.size(); 1585 for (int i = 0; i < numAdded; i++) { 1586 Fragment f = mAdded.get(i); 1587 moveFragmentToExpectedState(f); 1588 if (f.mLoaderManager != null) { 1589 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 1590 } 1591 } 1592 } 1593 1594 // Now iterate through all active fragments. These will include those that are removed 1595 // and detached. 1596 final int numActive = mActive.size(); 1597 for (int i = 0; i < numActive; i++) { 1598 Fragment f = mActive.get(i); 1599 if (f != null && (f.mRemoving || f.mDetached) && !f.mIsNewlyAdded) { 1600 moveFragmentToExpectedState(f); 1601 if (f.mLoaderManager != null) { 1602 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 1603 } 1604 } 1605 } 1606 1607 if (!loadersRunning) { 1608 startPendingDeferredFragments(); 1609 } 1610 1611 if (mNeedMenuInvalidate && mHost != null && mCurState == Fragment.RESUMED) { 1612 mHost.onSupportInvalidateOptionsMenu(); 1613 mNeedMenuInvalidate = false; 1614 } 1615 } 1616 } 1617 1618 void startPendingDeferredFragments() { 1619 if (mActive == null) return; 1620 1621 for (int i=0; i<mActive.size(); i++) { 1622 Fragment f = mActive.get(i); 1623 if (f != null) { 1624 performPendingDeferredStart(f); 1625 } 1626 } 1627 } 1628 1629 void makeActive(Fragment f) { 1630 if (f.mIndex >= 0) { 1631 return; 1632 } 1633 1634 if (mAvailIndices == null || mAvailIndices.size() <= 0) { 1635 if (mActive == null) { 1636 mActive = new ArrayList<Fragment>(); 1637 } 1638 f.setIndex(mActive.size(), mParent); 1639 mActive.add(f); 1640 1641 } else { 1642 f.setIndex(mAvailIndices.remove(mAvailIndices.size()-1), mParent); 1643 mActive.set(f.mIndex, f); 1644 } 1645 if (DEBUG) Log.v(TAG, "Allocated fragment index " + f); 1646 } 1647 1648 void makeInactive(Fragment f) { 1649 if (f.mIndex < 0) { 1650 return; 1651 } 1652 1653 if (DEBUG) Log.v(TAG, "Freeing fragment index " + f); 1654 mActive.set(f.mIndex, null); 1655 if (mAvailIndices == null) { 1656 mAvailIndices = new ArrayList<Integer>(); 1657 } 1658 mAvailIndices.add(f.mIndex); 1659 mHost.inactivateFragment(f.mWho); 1660 f.initState(); 1661 } 1662 1663 public void addFragment(Fragment fragment, boolean moveToStateNow) { 1664 if (mAdded == null) { 1665 mAdded = new ArrayList<Fragment>(); 1666 } 1667 if (DEBUG) Log.v(TAG, "add: " + fragment); 1668 makeActive(fragment); 1669 if (!fragment.mDetached) { 1670 if (mAdded.contains(fragment)) { 1671 throw new IllegalStateException("Fragment already added: " + fragment); 1672 } 1673 mAdded.add(fragment); 1674 fragment.mAdded = true; 1675 fragment.mRemoving = false; 1676 if (fragment.mView == null) { 1677 fragment.mHiddenChanged = false; 1678 } 1679 if (fragment.mHasMenu && fragment.mMenuVisible) { 1680 mNeedMenuInvalidate = true; 1681 } 1682 if (moveToStateNow) { 1683 moveToState(fragment); 1684 } 1685 } 1686 } 1687 1688 public void removeFragment(Fragment fragment) { 1689 if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); 1690 final boolean inactive = !fragment.isInBackStack(); 1691 if (!fragment.mDetached || inactive) { 1692 if (mAdded != null) { 1693 mAdded.remove(fragment); 1694 } 1695 if (fragment.mHasMenu && fragment.mMenuVisible) { 1696 mNeedMenuInvalidate = true; 1697 } 1698 fragment.mAdded = false; 1699 fragment.mRemoving = true; 1700 } 1701 } 1702 1703 /** 1704 * Marks a fragment as hidden to be later animated in with 1705 * {@link #completeShowHideFragment(Fragment)}. 1706 * 1707 * @param fragment The fragment to be shown. 1708 */ 1709 public void hideFragment(Fragment fragment) { 1710 if (DEBUG) Log.v(TAG, "hide: " + fragment); 1711 if (!fragment.mHidden) { 1712 fragment.mHidden = true; 1713 // Toggle hidden changed so that if a fragment goes through show/hide/show 1714 // it doesn't go through the animation. 1715 fragment.mHiddenChanged = !fragment.mHiddenChanged; 1716 } 1717 } 1718 1719 /** 1720 * Marks a fragment as shown to be later animated in with 1721 * {@link #completeShowHideFragment(Fragment)}. 1722 * 1723 * @param fragment The fragment to be shown. 1724 */ 1725 public void showFragment(Fragment fragment) { 1726 if (DEBUG) Log.v(TAG, "show: " + fragment); 1727 if (fragment.mHidden) { 1728 fragment.mHidden = false; 1729 // Toggle hidden changed so that if a fragment goes through show/hide/show 1730 // it doesn't go through the animation. 1731 fragment.mHiddenChanged = !fragment.mHiddenChanged; 1732 } 1733 } 1734 1735 public void detachFragment(Fragment fragment) { 1736 if (DEBUG) Log.v(TAG, "detach: " + fragment); 1737 if (!fragment.mDetached) { 1738 fragment.mDetached = true; 1739 if (fragment.mAdded) { 1740 // We are not already in back stack, so need to remove the fragment. 1741 if (mAdded != null) { 1742 if (DEBUG) Log.v(TAG, "remove from detach: " + fragment); 1743 mAdded.remove(fragment); 1744 } 1745 if (fragment.mHasMenu && fragment.mMenuVisible) { 1746 mNeedMenuInvalidate = true; 1747 } 1748 fragment.mAdded = false; 1749 } 1750 } 1751 } 1752 1753 public void attachFragment(Fragment fragment) { 1754 if (DEBUG) Log.v(TAG, "attach: " + fragment); 1755 if (fragment.mDetached) { 1756 fragment.mDetached = false; 1757 if (!fragment.mAdded) { 1758 if (mAdded == null) { 1759 mAdded = new ArrayList<Fragment>(); 1760 } 1761 if (mAdded.contains(fragment)) { 1762 throw new IllegalStateException("Fragment already added: " + fragment); 1763 } 1764 if (DEBUG) Log.v(TAG, "add from attach: " + fragment); 1765 mAdded.add(fragment); 1766 fragment.mAdded = true; 1767 if (fragment.mHasMenu && fragment.mMenuVisible) { 1768 mNeedMenuInvalidate = true; 1769 } 1770 } 1771 } 1772 } 1773 1774 @Override 1775 public Fragment findFragmentById(int id) { 1776 if (mAdded != null) { 1777 // First look through added fragments. 1778 for (int i=mAdded.size()-1; i>=0; i--) { 1779 Fragment f = mAdded.get(i); 1780 if (f != null && f.mFragmentId == id) { 1781 return f; 1782 } 1783 } 1784 } 1785 if (mActive != null) { 1786 // Now for any known fragment. 1787 for (int i=mActive.size()-1; i>=0; i--) { 1788 Fragment f = mActive.get(i); 1789 if (f != null && f.mFragmentId == id) { 1790 return f; 1791 } 1792 } 1793 } 1794 return null; 1795 } 1796 1797 @Override 1798 public Fragment findFragmentByTag(String tag) { 1799 if (mAdded != null && tag != null) { 1800 // First look through added fragments. 1801 for (int i=mAdded.size()-1; i>=0; i--) { 1802 Fragment f = mAdded.get(i); 1803 if (f != null && tag.equals(f.mTag)) { 1804 return f; 1805 } 1806 } 1807 } 1808 if (mActive != null && tag != null) { 1809 // Now for any known fragment. 1810 for (int i=mActive.size()-1; i>=0; i--) { 1811 Fragment f = mActive.get(i); 1812 if (f != null && tag.equals(f.mTag)) { 1813 return f; 1814 } 1815 } 1816 } 1817 return null; 1818 } 1819 1820 public Fragment findFragmentByWho(String who) { 1821 if (mActive != null && who != null) { 1822 for (int i=mActive.size()-1; i>=0; i--) { 1823 Fragment f = mActive.get(i); 1824 if (f != null && (f=f.findFragmentByWho(who)) != null) { 1825 return f; 1826 } 1827 } 1828 } 1829 return null; 1830 } 1831 1832 private void checkStateLoss() { 1833 if (mStateSaved) { 1834 throw new IllegalStateException( 1835 "Can not perform this action after onSaveInstanceState"); 1836 } 1837 if (mNoTransactionsBecause != null) { 1838 throw new IllegalStateException( 1839 "Can not perform this action inside of " + mNoTransactionsBecause); 1840 } 1841 } 1842 1843 /** 1844 * Adds an action to the queue of pending actions. 1845 * 1846 * @param action the action to add 1847 * @param allowStateLoss whether to allow loss of state information 1848 * @throws IllegalStateException if the activity has been destroyed 1849 */ 1850 public void enqueueAction(OpGenerator action, boolean allowStateLoss) { 1851 if (!allowStateLoss) { 1852 checkStateLoss(); 1853 } 1854 synchronized (this) { 1855 if (mDestroyed || mHost == null) { 1856 throw new IllegalStateException("Activity has been destroyed"); 1857 } 1858 if (mPendingActions == null) { 1859 mPendingActions = new ArrayList<>(); 1860 } 1861 mPendingActions.add(action); 1862 scheduleCommit(); 1863 } 1864 } 1865 1866 /** 1867 * Schedules the execution when one hasn't been scheduled already. This should happen 1868 * the first time {@link #enqueueAction(OpGenerator, boolean)} is called or when 1869 * a postponed transaction has been started with 1870 * {@link Fragment#startPostponedEnterTransition()} 1871 */ 1872 private void scheduleCommit() { 1873 synchronized (this) { 1874 boolean postponeReady = 1875 mPostponedTransactions != null && !mPostponedTransactions.isEmpty(); 1876 boolean pendingReady = mPendingActions != null && mPendingActions.size() == 1; 1877 if (postponeReady || pendingReady) { 1878 mHost.getHandler().removeCallbacks(mExecCommit); 1879 mHost.getHandler().post(mExecCommit); 1880 } 1881 } 1882 } 1883 1884 public int allocBackStackIndex(BackStackRecord bse) { 1885 synchronized (this) { 1886 if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) { 1887 if (mBackStackIndices == null) { 1888 mBackStackIndices = new ArrayList<BackStackRecord>(); 1889 } 1890 int index = mBackStackIndices.size(); 1891 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1892 mBackStackIndices.add(bse); 1893 return index; 1894 1895 } else { 1896 int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1); 1897 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1898 mBackStackIndices.set(index, bse); 1899 return index; 1900 } 1901 } 1902 } 1903 1904 public void setBackStackIndex(int index, BackStackRecord bse) { 1905 synchronized (this) { 1906 if (mBackStackIndices == null) { 1907 mBackStackIndices = new ArrayList<BackStackRecord>(); 1908 } 1909 int N = mBackStackIndices.size(); 1910 if (index < N) { 1911 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1912 mBackStackIndices.set(index, bse); 1913 } else { 1914 while (N < index) { 1915 mBackStackIndices.add(null); 1916 if (mAvailBackStackIndices == null) { 1917 mAvailBackStackIndices = new ArrayList<Integer>(); 1918 } 1919 if (DEBUG) Log.v(TAG, "Adding available back stack index " + N); 1920 mAvailBackStackIndices.add(N); 1921 N++; 1922 } 1923 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1924 mBackStackIndices.add(bse); 1925 } 1926 } 1927 } 1928 1929 public void freeBackStackIndex(int index) { 1930 synchronized (this) { 1931 mBackStackIndices.set(index, null); 1932 if (mAvailBackStackIndices == null) { 1933 mAvailBackStackIndices = new ArrayList<Integer>(); 1934 } 1935 if (DEBUG) Log.v(TAG, "Freeing back stack index " + index); 1936 mAvailBackStackIndices.add(index); 1937 } 1938 } 1939 1940 /** 1941 * Broken out from exec*, this prepares for gathering and executing operations. 1942 * 1943 * @param allowStateLoss true if state loss should be ignored or false if it should be 1944 * checked. 1945 */ 1946 private void ensureExecReady(boolean allowStateLoss) { 1947 if (mExecutingActions) { 1948 throw new IllegalStateException("FragmentManager is already executing transactions"); 1949 } 1950 1951 if (Looper.myLooper() != mHost.getHandler().getLooper()) { 1952 throw new IllegalStateException("Must be called from main thread of fragment host"); 1953 } 1954 1955 if (!allowStateLoss) { 1956 checkStateLoss(); 1957 } 1958 1959 if (mTmpRecords == null) { 1960 mTmpRecords = new ArrayList<>(); 1961 mTmpIsPop = new ArrayList<>(); 1962 } 1963 executePostponedTransaction(null, null); 1964 } 1965 1966 public void execSingleAction(OpGenerator action, boolean allowStateLoss) { 1967 ensureExecReady(allowStateLoss); 1968 if (action.generateOps(mTmpRecords, mTmpIsPop)) { 1969 mExecutingActions = true; 1970 try { 1971 optimizeAndExecuteOps(mTmpRecords, mTmpIsPop); 1972 } finally { 1973 cleanupExec(); 1974 } 1975 } 1976 1977 doPendingDeferredStart(); 1978 } 1979 1980 /** 1981 * Broken out of exec*, this cleans up the mExecutingActions and the temporary structures 1982 * used in executing operations. 1983 */ 1984 private void cleanupExec() { 1985 mExecutingActions = false; 1986 mTmpIsPop.clear(); 1987 mTmpRecords.clear(); 1988 } 1989 1990 /** 1991 * Only call from main thread! 1992 */ 1993 public boolean execPendingActions() { 1994 ensureExecReady(true); 1995 1996 boolean didSomething = false; 1997 while (generateOpsForPendingActions(mTmpRecords, mTmpIsPop)) { 1998 mExecutingActions = true; 1999 try { 2000 optimizeAndExecuteOps(mTmpRecords, mTmpIsPop); 2001 } finally { 2002 cleanupExec(); 2003 } 2004 didSomething = true; 2005 } 2006 2007 doPendingDeferredStart(); 2008 2009 return didSomething; 2010 } 2011 2012 /** 2013 * Complete the execution of transactions that have previously been postponed, but are 2014 * now ready. 2015 */ 2016 private void executePostponedTransaction(ArrayList<BackStackRecord> records, 2017 ArrayList<Boolean> isRecordPop) { 2018 int numPostponed = mPostponedTransactions == null ? 0 : mPostponedTransactions.size(); 2019 for (int i = 0; i < numPostponed; i++) { 2020 StartEnterTransitionListener listener = mPostponedTransactions.get(i); 2021 if (records != null && !listener.mIsBack) { 2022 int index = records.indexOf(listener.mRecord); 2023 if (index != -1 && isRecordPop.get(index)) { 2024 listener.cancelTransaction(); 2025 continue; 2026 } 2027 } 2028 if (listener.isReady() || (records != null 2029 && listener.mRecord.interactsWith(records, 0, records.size()))) { 2030 mPostponedTransactions.remove(i); 2031 i--; 2032 numPostponed--; 2033 int index; 2034 if (records != null && !listener.mIsBack 2035 && (index = records.indexOf(listener.mRecord)) != -1 2036 && isRecordPop.get(index)) { 2037 // This is popping a postponed transaction 2038 listener.cancelTransaction(); 2039 } else { 2040 listener.completeTransaction(); 2041 } 2042 } 2043 } 2044 } 2045 2046 /** 2047 * Optimizes BackStackRecord operations. This method merges operations of proximate records 2048 * that allow optimization. See {@link FragmentTransaction#setAllowOptimization(boolean)}. 2049 * <p> 2050 * For example, a transaction that adds to the back stack and then another that pops that 2051 * back stack record will be optimized. 2052 * <p> 2053 * Likewise, two transactions committed that are executed at the same time will be optimized 2054 * as well as two pop operations executed together. 2055 * 2056 * @param records The records pending execution 2057 * @param isRecordPop The direction that these records are being run. 2058 */ 2059 private void optimizeAndExecuteOps(ArrayList<BackStackRecord> records, 2060 ArrayList<Boolean> isRecordPop) { 2061 if (records == null || records.isEmpty()) { 2062 return; 2063 } 2064 2065 if (isRecordPop == null || records.size() != isRecordPop.size()) { 2066 throw new IllegalStateException("Internal error with the back stack records"); 2067 } 2068 2069 // Force start of any postponed transactions that interact with scheduled transactions: 2070 executePostponedTransaction(records, isRecordPop); 2071 2072 final int numRecords = records.size(); 2073 int startIndex = 0; 2074 for (int recordNum = 0; recordNum < numRecords; recordNum++) { 2075 final boolean canOptimize = records.get(recordNum).mAllowOptimization; 2076 if (!canOptimize) { 2077 // execute all previous transactions 2078 if (startIndex != recordNum) { 2079 executeOpsTogether(records, isRecordPop, startIndex, recordNum); 2080 } 2081 // execute all unoptimized together 2082 int optimizeEnd; 2083 for (optimizeEnd = recordNum + 1; optimizeEnd < numRecords; optimizeEnd++) { 2084 if (records.get(optimizeEnd).mAllowOptimization) { 2085 break; 2086 } 2087 } 2088 executeOpsTogether(records, isRecordPop, recordNum, optimizeEnd); 2089 startIndex = optimizeEnd; 2090 recordNum = optimizeEnd - 1; 2091 } 2092 } 2093 if (startIndex != numRecords) { 2094 executeOpsTogether(records, isRecordPop, startIndex, numRecords); 2095 } 2096 } 2097 2098 /** 2099 * Optimizes a subset of a list of BackStackRecords, all of which either allow optimization or 2100 * do not allow optimization. 2101 * @param records A list of BackStackRecords that are to be optimized 2102 * @param isRecordPop The direction that these records are being run. 2103 * @param startIndex The index of the first record in <code>records</code> to be optimized 2104 * @param endIndex One more than the final record index in <code>records</code> to optimize. 2105 */ 2106 private void executeOpsTogether(ArrayList<BackStackRecord> records, 2107 ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { 2108 final boolean allowOptimization = records.get(startIndex).mAllowOptimization; 2109 boolean addToBackStack = false; 2110 if (mTmpAddedFragments == null) { 2111 mTmpAddedFragments = new ArrayList<>(); 2112 } else { 2113 mTmpAddedFragments.clear(); 2114 } 2115 if (mAdded != null) { 2116 mTmpAddedFragments.addAll(mAdded); 2117 } 2118 for (int recordNum = startIndex; recordNum < endIndex; recordNum++) { 2119 final BackStackRecord record = records.get(recordNum); 2120 final boolean isPop = isRecordPop.get(recordNum); 2121 if (!isPop) { 2122 record.expandReplaceOps(mTmpAddedFragments); 2123 } 2124 final int bumpAmount = isPop ? -1 : 1; 2125 record.bumpBackStackNesting(bumpAmount); 2126 addToBackStack = addToBackStack || record.mAddToBackStack; 2127 } 2128 mTmpAddedFragments.clear(); 2129 2130 if (!allowOptimization) { 2131 FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, endIndex, 2132 false); 2133 } 2134 executeOps(records, isRecordPop, startIndex, endIndex); 2135 2136 int postponeIndex = endIndex; 2137 if (allowOptimization) { 2138 moveFragmentsToInvisible(); 2139 postponeIndex = postponePostponableTransactions(records, isRecordPop, 2140 startIndex, endIndex); 2141 } 2142 2143 if (postponeIndex != startIndex && allowOptimization) { 2144 // need to run something now 2145 FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, 2146 postponeIndex, true); 2147 moveToState(mCurState, true); 2148 } 2149 2150 for (int recordNum = startIndex; recordNum < endIndex; recordNum++) { 2151 final BackStackRecord record = records.get(recordNum); 2152 final boolean isPop = isRecordPop.get(recordNum); 2153 if (isPop && record.mIndex >= 0) { 2154 freeBackStackIndex(record.mIndex); 2155 record.mIndex = -1; 2156 } 2157 } 2158 if (addToBackStack) { 2159 reportBackStackChanged(); 2160 } 2161 } 2162 2163 /** 2164 * Examine all transactions and determine which ones are marked as postponed. Those will 2165 * have their operations rolled back and moved to the end of the record list (up to endIndex). 2166 * It will also add the postponed transaction to the queue. 2167 * 2168 * @param records A list of BackStackRecords that should be checked. 2169 * @param isRecordPop The direction that these records are being run. 2170 * @param startIndex The index of the first record in <code>records</code> to be checked 2171 * @param endIndex One more than the final record index in <code>records</code> to be checked. 2172 * @return The index of the first postponed transaction or endIndex if no transaction was 2173 * postponed. 2174 */ 2175 private int postponePostponableTransactions(ArrayList<BackStackRecord> records, 2176 ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { 2177 int postponeIndex = endIndex; 2178 for (int i = endIndex - 1; i >= startIndex; i--) { 2179 final BackStackRecord record = records.get(i); 2180 final boolean isPop = isRecordPop.get(i); 2181 boolean isPostponed = record.isPostponed() 2182 && !record.interactsWith(records, i + 1, endIndex); 2183 if (isPostponed) { 2184 if (mPostponedTransactions == null) { 2185 mPostponedTransactions = new ArrayList<>(); 2186 } 2187 StartEnterTransitionListener listener = 2188 new StartEnterTransitionListener(record, isPop); 2189 mPostponedTransactions.add(listener); 2190 record.setOnStartPostponedListener(listener); 2191 2192 // roll back the transaction 2193 if (isPop) { 2194 record.executeOps(); 2195 } else { 2196 record.executePopOps(); 2197 } 2198 2199 // move to the end 2200 postponeIndex--; 2201 if (i != postponeIndex) { 2202 records.remove(i); 2203 records.add(postponeIndex, record); 2204 } 2205 2206 // different views may be visible now 2207 moveFragmentsToInvisible(); 2208 } 2209 } 2210 return postponeIndex; 2211 } 2212 2213 /** 2214 * When a postponed transaction is ready to be started, this completes the transaction, 2215 * removing, hiding, or showing views as well as starting the animations and transitions. 2216 * <p> 2217 * {@code runtransitions} is set to false when the transaction postponement was interrupted 2218 * abnormally -- normally by a new transaction being started that affects the postponed 2219 * transaction. 2220 * 2221 * @param record The transaction to run 2222 * @param isPop true if record is popping or false if it is adding 2223 * @param runTransitions true if the fragment transition should be run or false otherwise. 2224 * @param moveToState true if the state should be changed after executing the operations. 2225 * This is false when the transaction is canceled when a postponed 2226 * transaction is popped. 2227 */ 2228 private void completeExecute(BackStackRecord record, boolean isPop, boolean runTransitions, 2229 boolean moveToState) { 2230 ArrayList<BackStackRecord> records = new ArrayList<>(1); 2231 ArrayList<Boolean> isRecordPop = new ArrayList<>(1); 2232 records.add(record); 2233 isRecordPop.add(isPop); 2234 executeOps(records, isRecordPop, 0, 1); 2235 if (runTransitions) { 2236 FragmentTransition.startTransitions(this, records, isRecordPop, 0, 1, true); 2237 } 2238 if (moveToState) { 2239 moveToState(mCurState, true); 2240 } else if (mActive != null) { 2241 final int numActive = mActive.size(); 2242 for (int i = 0; i < numActive; i++) { 2243 // Allow added fragments to be removed during the pop since we aren't going 2244 // to move them to the final state with moveToState(mCurState). 2245 Fragment fragment = mActive.get(i); 2246 if (fragment.mView != null && fragment.mIsNewlyAdded 2247 && record.interactsWith(fragment.mContainerId)) { 2248 fragment.mIsNewlyAdded = false; 2249 } 2250 } 2251 } 2252 } 2253 2254 /** 2255 * Find a fragment within the fragment's container whose View should be below the passed 2256 * fragment. {@code null} is returned when the fragment has no View or if there should be 2257 * no fragment with a View below the given fragment. 2258 * 2259 * As an example, if mAdded has two Fragments with Views sharing the same container: 2260 * FragmentA 2261 * FragmentB 2262 * 2263 * Then, when processing FragmentB, FragmentA will be returned. If, however, FragmentA 2264 * had no View, null would be returned. 2265 * 2266 * @param f The fragment that may be on top of another fragment. 2267 * @return The fragment with a View under f, if one exists or null if f has no View or 2268 * there are no fragments with Views in the same container. 2269 */ 2270 private Fragment findFragmentUnder(Fragment f) { 2271 final ViewGroup container = f.mContainer; 2272 final View view = f.mView; 2273 2274 if (container == null || view == null) { 2275 return null; 2276 } 2277 2278 final int fragmentIndex = mAdded.indexOf(f); 2279 for (int i = fragmentIndex - 1; i >= 0; i--) { 2280 Fragment underFragment = mAdded.get(i); 2281 if (underFragment.mContainer == container && underFragment.mView != null) { 2282 // Found the fragment under this one 2283 return underFragment; 2284 } 2285 } 2286 return null; 2287 } 2288 2289 /** 2290 * Run the operations in the BackStackRecords, either to push or pop. 2291 * 2292 * @param records The list of records whose operations should be run. 2293 * @param isRecordPop The direction that these records are being run. 2294 * @param startIndex The index of the first entry in records to run. 2295 * @param endIndex One past the index of the final entry in records to run. 2296 */ 2297 private static void executeOps(ArrayList<BackStackRecord> records, 2298 ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { 2299 for (int i = startIndex; i < endIndex; i++) { 2300 final BackStackRecord record = records.get(i); 2301 final boolean isPop = isRecordPop.get(i); 2302 if (isPop) { 2303 record.executePopOps(); 2304 } else { 2305 record.executeOps(); 2306 } 2307 } 2308 } 2309 2310 /** 2311 * Ensure that fragments that are added are moved to at least the CREATED state. 2312 * Any newly-added Views are made INVISIBLE so that the Transaction can be postponed 2313 * with {@link Fragment#postponeEnterTransition()}. 2314 */ 2315 private void moveFragmentsToInvisible() { 2316 if (mCurState < Fragment.CREATED) { 2317 return; 2318 } 2319 // We want to leave the fragment in the started state 2320 final int state = Math.min(mCurState, Fragment.STARTED); 2321 final int numAdded = mAdded == null ? 0 : mAdded.size(); 2322 for (int i = 0; i < numAdded; i++) { 2323 Fragment fragment = mAdded.get(i); 2324 if (fragment.mState < state) { 2325 moveToState(fragment, state, fragment.getNextAnim(), fragment.getNextTransition(), 2326 false); 2327 if (fragment.mView != null && !fragment.mHidden && fragment.mIsNewlyAdded) { 2328 fragment.mView.setVisibility(View.INVISIBLE); 2329 } 2330 } 2331 } 2332 } 2333 2334 /** 2335 * Starts all postponed transactions regardless of whether they are ready or not. 2336 */ 2337 private void forcePostponedTransactions() { 2338 if (mPostponedTransactions != null) { 2339 while (!mPostponedTransactions.isEmpty()) { 2340 mPostponedTransactions.remove(0).completeTransaction(); 2341 } 2342 } 2343 } 2344 2345 /** 2346 * Ends the animations of fragments so that they immediately reach the end state. 2347 * This is used prior to saving the state so that the correct state is saved. 2348 */ 2349 private void endAnimatingAwayFragments() { 2350 final int numFragments = mActive == null ? 0 : mActive.size(); 2351 for (int i = 0; i < numFragments; i++) { 2352 Fragment fragment = mActive.get(i); 2353 if (fragment != null && fragment.getAnimatingAway() != null) { 2354 // Give up waiting for the animation and just end it. 2355 final int stateAfterAnimating = fragment.getStateAfterAnimating(); 2356 final View animatingAway = fragment.getAnimatingAway(); 2357 fragment.setAnimatingAway(null); 2358 animatingAway.clearAnimation(); 2359 moveToState(fragment, stateAfterAnimating, 0, 0, false); 2360 } 2361 } 2362 } 2363 2364 /** 2365 * Adds all records in the pending actions to records and whether they are add or pop 2366 * operations to isPop. After executing, the pending actions will be empty. 2367 * 2368 * @param records All pending actions will generate BackStackRecords added to this. 2369 * This contains the transactions, in order, to execute. 2370 * @param isPop All pending actions will generate booleans to add to this. This contains 2371 * an entry for each entry in records to indicate whether or not it is a 2372 * pop action. 2373 */ 2374 private boolean generateOpsForPendingActions(ArrayList<BackStackRecord> records, 2375 ArrayList<Boolean> isPop) { 2376 int numActions; 2377 synchronized (this) { 2378 if (mPendingActions == null || mPendingActions.size() == 0) { 2379 return false; 2380 } 2381 2382 numActions = mPendingActions.size(); 2383 for (int i = 0; i < numActions; i++) { 2384 mPendingActions.get(i).generateOps(records, isPop); 2385 } 2386 mPendingActions.clear(); 2387 mHost.getHandler().removeCallbacks(mExecCommit); 2388 } 2389 return numActions > 0; 2390 } 2391 2392 void doPendingDeferredStart() { 2393 if (mHavePendingDeferredStart) { 2394 boolean loadersRunning = false; 2395 for (int i = 0; i < mActive.size(); i++) { 2396 Fragment f = mActive.get(i); 2397 if (f != null && f.mLoaderManager != null) { 2398 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 2399 } 2400 } 2401 if (!loadersRunning) { 2402 mHavePendingDeferredStart = false; 2403 startPendingDeferredFragments(); 2404 } 2405 } 2406 } 2407 2408 void reportBackStackChanged() { 2409 if (mBackStackChangeListeners != null) { 2410 for (int i=0; i<mBackStackChangeListeners.size(); i++) { 2411 mBackStackChangeListeners.get(i).onBackStackChanged(); 2412 } 2413 } 2414 } 2415 2416 void addBackStackState(BackStackRecord state) { 2417 if (mBackStack == null) { 2418 mBackStack = new ArrayList<BackStackRecord>(); 2419 } 2420 mBackStack.add(state); 2421 reportBackStackChanged(); 2422 } 2423 2424 @SuppressWarnings("unused") 2425 boolean popBackStackState(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, 2426 String name, int id, int flags) { 2427 if (mBackStack == null) { 2428 return false; 2429 } 2430 if (name == null && id < 0 && (flags & POP_BACK_STACK_INCLUSIVE) == 0) { 2431 int last = mBackStack.size() - 1; 2432 if (last < 0) { 2433 return false; 2434 } 2435 records.add(mBackStack.remove(last)); 2436 isRecordPop.add(true); 2437 } else { 2438 int index = -1; 2439 if (name != null || id >= 0) { 2440 // If a name or ID is specified, look for that place in 2441 // the stack. 2442 index = mBackStack.size()-1; 2443 while (index >= 0) { 2444 BackStackRecord bss = mBackStack.get(index); 2445 if (name != null && name.equals(bss.getName())) { 2446 break; 2447 } 2448 if (id >= 0 && id == bss.mIndex) { 2449 break; 2450 } 2451 index--; 2452 } 2453 if (index < 0) { 2454 return false; 2455 } 2456 if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) { 2457 index--; 2458 // Consume all following entries that match. 2459 while (index >= 0) { 2460 BackStackRecord bss = mBackStack.get(index); 2461 if ((name != null && name.equals(bss.getName())) 2462 || (id >= 0 && id == bss.mIndex)) { 2463 index--; 2464 continue; 2465 } 2466 break; 2467 } 2468 } 2469 } 2470 if (index == mBackStack.size()-1) { 2471 return false; 2472 } 2473 for (int i = mBackStack.size() - 1; i > index; i--) { 2474 records.add(mBackStack.remove(i)); 2475 isRecordPop.add(true); 2476 } 2477 } 2478 return true; 2479 } 2480 2481 FragmentManagerNonConfig retainNonConfig() { 2482 ArrayList<Fragment> fragments = null; 2483 ArrayList<FragmentManagerNonConfig> childFragments = null; 2484 if (mActive != null) { 2485 for (int i=0; i<mActive.size(); i++) { 2486 Fragment f = mActive.get(i); 2487 if (f != null) { 2488 if (f.mRetainInstance) { 2489 if (fragments == null) { 2490 fragments = new ArrayList<Fragment>(); 2491 } 2492 fragments.add(f); 2493 f.mRetaining = true; 2494 f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1; 2495 if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f); 2496 } 2497 boolean addedChild = false; 2498 if (f.mChildFragmentManager != null) { 2499 FragmentManagerNonConfig child = f.mChildFragmentManager.retainNonConfig(); 2500 if (child != null) { 2501 if (childFragments == null) { 2502 childFragments = new ArrayList<FragmentManagerNonConfig>(); 2503 for (int j = 0; j < i; j++) { 2504 childFragments.add(null); 2505 } 2506 } 2507 childFragments.add(child); 2508 addedChild = true; 2509 } 2510 } 2511 if (childFragments != null && !addedChild) { 2512 childFragments.add(null); 2513 } 2514 } 2515 } 2516 } 2517 if (fragments == null && childFragments == null) { 2518 return null; 2519 } 2520 return new FragmentManagerNonConfig(fragments, childFragments); 2521 } 2522 2523 void saveFragmentViewState(Fragment f) { 2524 if (f.mInnerView == null) { 2525 return; 2526 } 2527 if (mStateArray == null) { 2528 mStateArray = new SparseArray<Parcelable>(); 2529 } else { 2530 mStateArray.clear(); 2531 } 2532 f.mInnerView.saveHierarchyState(mStateArray); 2533 if (mStateArray.size() > 0) { 2534 f.mSavedViewState = mStateArray; 2535 mStateArray = null; 2536 } 2537 } 2538 2539 Bundle saveFragmentBasicState(Fragment f) { 2540 Bundle result = null; 2541 2542 if (mStateBundle == null) { 2543 mStateBundle = new Bundle(); 2544 } 2545 f.performSaveInstanceState(mStateBundle); 2546 dispatchOnFragmentSaveInstanceState(f, mStateBundle, false); 2547 if (!mStateBundle.isEmpty()) { 2548 result = mStateBundle; 2549 mStateBundle = null; 2550 } 2551 2552 if (f.mView != null) { 2553 saveFragmentViewState(f); 2554 } 2555 if (f.mSavedViewState != null) { 2556 if (result == null) { 2557 result = new Bundle(); 2558 } 2559 result.putSparseParcelableArray( 2560 FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState); 2561 } 2562 if (!f.mUserVisibleHint) { 2563 if (result == null) { 2564 result = new Bundle(); 2565 } 2566 // Only add this if it's not the default value 2567 result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint); 2568 } 2569 2570 return result; 2571 } 2572 2573 Parcelable saveAllState() { 2574 // Make sure all pending operations have now been executed to get 2575 // our state update-to-date. 2576 forcePostponedTransactions(); 2577 endAnimatingAwayFragments(); 2578 execPendingActions(); 2579 2580 if (HONEYCOMB) { 2581 // As of Honeycomb, we save state after pausing. Prior to that 2582 // it is before pausing. With fragments this is an issue, since 2583 // there are many things you may do after pausing but before 2584 // stopping that change the fragment state. For those older 2585 // devices, we will not at this point say that we have saved 2586 // the state, so we will allow them to continue doing fragment 2587 // transactions. This retains the same semantics as Honeycomb, 2588 // though you do have the risk of losing the very most recent state 2589 // if the process is killed... we'll live with that. 2590 mStateSaved = true; 2591 } 2592 2593 if (mActive == null || mActive.size() <= 0) { 2594 return null; 2595 } 2596 2597 // First collect all active fragments. 2598 int N = mActive.size(); 2599 FragmentState[] active = new FragmentState[N]; 2600 boolean haveFragments = false; 2601 for (int i=0; i<N; i++) { 2602 Fragment f = mActive.get(i); 2603 if (f != null) { 2604 if (f.mIndex < 0) { 2605 throwException(new IllegalStateException( 2606 "Failure saving state: active " + f 2607 + " has cleared index: " + f.mIndex)); 2608 } 2609 2610 haveFragments = true; 2611 2612 FragmentState fs = new FragmentState(f); 2613 active[i] = fs; 2614 2615 if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) { 2616 fs.mSavedFragmentState = saveFragmentBasicState(f); 2617 2618 if (f.mTarget != null) { 2619 if (f.mTarget.mIndex < 0) { 2620 throwException(new IllegalStateException( 2621 "Failure saving state: " + f 2622 + " has target not in fragment manager: " + f.mTarget)); 2623 } 2624 if (fs.mSavedFragmentState == null) { 2625 fs.mSavedFragmentState = new Bundle(); 2626 } 2627 putFragment(fs.mSavedFragmentState, 2628 FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget); 2629 if (f.mTargetRequestCode != 0) { 2630 fs.mSavedFragmentState.putInt( 2631 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 2632 f.mTargetRequestCode); 2633 } 2634 } 2635 2636 } else { 2637 fs.mSavedFragmentState = f.mSavedFragmentState; 2638 } 2639 2640 if (DEBUG) Log.v(TAG, "Saved state of " + f + ": " 2641 + fs.mSavedFragmentState); 2642 } 2643 } 2644 2645 if (!haveFragments) { 2646 if (DEBUG) Log.v(TAG, "saveAllState: no fragments!"); 2647 return null; 2648 } 2649 2650 int[] added = null; 2651 BackStackState[] backStack = null; 2652 2653 // Build list of currently added fragments. 2654 if (mAdded != null) { 2655 N = mAdded.size(); 2656 if (N > 0) { 2657 added = new int[N]; 2658 for (int i=0; i<N; i++) { 2659 added[i] = mAdded.get(i).mIndex; 2660 if (added[i] < 0) { 2661 throwException(new IllegalStateException( 2662 "Failure saving state: active " + mAdded.get(i) 2663 + " has cleared index: " + added[i])); 2664 } 2665 if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i 2666 + ": " + mAdded.get(i)); 2667 } 2668 } 2669 } 2670 2671 // Now save back stack. 2672 if (mBackStack != null) { 2673 N = mBackStack.size(); 2674 if (N > 0) { 2675 backStack = new BackStackState[N]; 2676 for (int i=0; i<N; i++) { 2677 backStack[i] = new BackStackState(mBackStack.get(i)); 2678 if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i 2679 + ": " + mBackStack.get(i)); 2680 } 2681 } 2682 } 2683 2684 FragmentManagerState fms = new FragmentManagerState(); 2685 fms.mActive = active; 2686 fms.mAdded = added; 2687 fms.mBackStack = backStack; 2688 return fms; 2689 } 2690 2691 void restoreAllState(Parcelable state, FragmentManagerNonConfig nonConfig) { 2692 // If there is no saved state at all, then there can not be 2693 // any nonConfig fragments either, so that is that. 2694 if (state == null) return; 2695 FragmentManagerState fms = (FragmentManagerState)state; 2696 if (fms.mActive == null) return; 2697 2698 List<FragmentManagerNonConfig> childNonConfigs = null; 2699 2700 // First re-attach any non-config instances we are retaining back 2701 // to their saved state, so we don't try to instantiate them again. 2702 if (nonConfig != null) { 2703 List<Fragment> nonConfigFragments = nonConfig.getFragments(); 2704 childNonConfigs = nonConfig.getChildNonConfigs(); 2705 final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0; 2706 for (int i = 0; i < count; i++) { 2707 Fragment f = nonConfigFragments.get(i); 2708 if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f); 2709 FragmentState fs = fms.mActive[f.mIndex]; 2710 fs.mInstance = f; 2711 f.mSavedViewState = null; 2712 f.mBackStackNesting = 0; 2713 f.mInLayout = false; 2714 f.mAdded = false; 2715 f.mTarget = null; 2716 if (fs.mSavedFragmentState != null) { 2717 fs.mSavedFragmentState.setClassLoader(mHost.getContext().getClassLoader()); 2718 f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray( 2719 FragmentManagerImpl.VIEW_STATE_TAG); 2720 f.mSavedFragmentState = fs.mSavedFragmentState; 2721 } 2722 } 2723 } 2724 2725 // Build the full list of active fragments, instantiating them from 2726 // their saved state. 2727 mActive = new ArrayList<>(fms.mActive.length); 2728 if (mAvailIndices != null) { 2729 mAvailIndices.clear(); 2730 } 2731 for (int i=0; i<fms.mActive.length; i++) { 2732 FragmentState fs = fms.mActive[i]; 2733 if (fs != null) { 2734 FragmentManagerNonConfig childNonConfig = null; 2735 if (childNonConfigs != null && i < childNonConfigs.size()) { 2736 childNonConfig = childNonConfigs.get(i); 2737 } 2738 Fragment f = fs.instantiate(mHost, mParent, childNonConfig); 2739 if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f); 2740 mActive.add(f); 2741 // Now that the fragment is instantiated (or came from being 2742 // retained above), clear mInstance in case we end up re-restoring 2743 // from this FragmentState again. 2744 fs.mInstance = null; 2745 } else { 2746 mActive.add(null); 2747 if (mAvailIndices == null) { 2748 mAvailIndices = new ArrayList<Integer>(); 2749 } 2750 if (DEBUG) Log.v(TAG, "restoreAllState: avail #" + i); 2751 mAvailIndices.add(i); 2752 } 2753 } 2754 2755 // Update the target of all retained fragments. 2756 if (nonConfig != null) { 2757 List<Fragment> nonConfigFragments = nonConfig.getFragments(); 2758 final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0; 2759 for (int i = 0; i < count; i++) { 2760 Fragment f = nonConfigFragments.get(i); 2761 if (f.mTargetIndex >= 0) { 2762 if (f.mTargetIndex < mActive.size()) { 2763 f.mTarget = mActive.get(f.mTargetIndex); 2764 } else { 2765 Log.w(TAG, "Re-attaching retained fragment " + f 2766 + " target no longer exists: " + f.mTargetIndex); 2767 f.mTarget = null; 2768 } 2769 } 2770 } 2771 } 2772 2773 // Build the list of currently added fragments. 2774 if (fms.mAdded != null) { 2775 mAdded = new ArrayList<Fragment>(fms.mAdded.length); 2776 for (int i=0; i<fms.mAdded.length; i++) { 2777 Fragment f = mActive.get(fms.mAdded[i]); 2778 if (f == null) { 2779 throwException(new IllegalStateException( 2780 "No instantiated fragment for index #" + fms.mAdded[i])); 2781 } 2782 f.mAdded = true; 2783 if (DEBUG) Log.v(TAG, "restoreAllState: added #" + i + ": " + f); 2784 if (mAdded.contains(f)) { 2785 throw new IllegalStateException("Already added!"); 2786 } 2787 mAdded.add(f); 2788 } 2789 } else { 2790 mAdded = null; 2791 } 2792 2793 // Build the back stack. 2794 if (fms.mBackStack != null) { 2795 mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length); 2796 for (int i=0; i<fms.mBackStack.length; i++) { 2797 BackStackRecord bse = fms.mBackStack[i].instantiate(this); 2798 if (DEBUG) { 2799 Log.v(TAG, "restoreAllState: back stack #" + i 2800 + " (index " + bse.mIndex + "): " + bse); 2801 LogWriter logw = new LogWriter(TAG); 2802 PrintWriter pw = new PrintWriter(logw); 2803 bse.dump(" ", pw, false); 2804 } 2805 mBackStack.add(bse); 2806 if (bse.mIndex >= 0) { 2807 setBackStackIndex(bse.mIndex, bse); 2808 } 2809 } 2810 } else { 2811 mBackStack = null; 2812 } 2813 } 2814 2815 public void attachController(FragmentHostCallback host, 2816 FragmentContainer container, Fragment parent) { 2817 if (mHost != null) throw new IllegalStateException("Already attached"); 2818 mHost = host; 2819 mContainer = container; 2820 mParent = parent; 2821 } 2822 2823 public void noteStateNotSaved() { 2824 mStateSaved = false; 2825 } 2826 2827 public void dispatchCreate() { 2828 mStateSaved = false; 2829 moveToState(Fragment.CREATED, false); 2830 } 2831 2832 public void dispatchActivityCreated() { 2833 mStateSaved = false; 2834 moveToState(Fragment.ACTIVITY_CREATED, false); 2835 } 2836 2837 public void dispatchStart() { 2838 mStateSaved = false; 2839 moveToState(Fragment.STARTED, false); 2840 } 2841 2842 public void dispatchResume() { 2843 mStateSaved = false; 2844 moveToState(Fragment.RESUMED, false); 2845 } 2846 2847 public void dispatchPause() { 2848 moveToState(Fragment.STARTED, false); 2849 } 2850 2851 public void dispatchStop() { 2852 // See saveAllState() for the explanation of this. We do this for 2853 // all platform versions, to keep our behavior more consistent between 2854 // them. 2855 mStateSaved = true; 2856 2857 moveToState(Fragment.STOPPED, false); 2858 } 2859 2860 public void dispatchReallyStop() { 2861 moveToState(Fragment.ACTIVITY_CREATED, false); 2862 } 2863 2864 public void dispatchDestroyView() { 2865 moveToState(Fragment.CREATED, false); 2866 } 2867 2868 public void dispatchDestroy() { 2869 mDestroyed = true; 2870 execPendingActions(); 2871 moveToState(Fragment.INITIALIZING, false); 2872 mHost = null; 2873 mContainer = null; 2874 mParent = null; 2875 } 2876 2877 public void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode) { 2878 if (mAdded == null) { 2879 return; 2880 } 2881 for (int i = mAdded.size() - 1; i >= 0; --i) { 2882 final android.support.v4.app.Fragment f = mAdded.get(i); 2883 if (f != null) { 2884 f.performMultiWindowModeChanged(isInMultiWindowMode); 2885 } 2886 } 2887 } 2888 2889 public void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode) { 2890 if (mAdded == null) { 2891 return; 2892 } 2893 for (int i = mAdded.size() - 1; i >= 0; --i) { 2894 final android.support.v4.app.Fragment f = mAdded.get(i); 2895 if (f != null) { 2896 f.performPictureInPictureModeChanged(isInPictureInPictureMode); 2897 } 2898 } 2899 } 2900 2901 public void dispatchConfigurationChanged(Configuration newConfig) { 2902 if (mAdded != null) { 2903 for (int i=0; i<mAdded.size(); i++) { 2904 Fragment f = mAdded.get(i); 2905 if (f != null) { 2906 f.performConfigurationChanged(newConfig); 2907 } 2908 } 2909 } 2910 } 2911 2912 public void dispatchLowMemory() { 2913 if (mAdded != null) { 2914 for (int i=0; i<mAdded.size(); i++) { 2915 Fragment f = mAdded.get(i); 2916 if (f != null) { 2917 f.performLowMemory(); 2918 } 2919 } 2920 } 2921 } 2922 2923 public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) { 2924 boolean show = false; 2925 ArrayList<Fragment> newMenus = null; 2926 if (mAdded != null) { 2927 for (int i=0; i<mAdded.size(); i++) { 2928 Fragment f = mAdded.get(i); 2929 if (f != null) { 2930 if (f.performCreateOptionsMenu(menu, inflater)) { 2931 show = true; 2932 if (newMenus == null) { 2933 newMenus = new ArrayList<Fragment>(); 2934 } 2935 newMenus.add(f); 2936 } 2937 } 2938 } 2939 } 2940 2941 if (mCreatedMenus != null) { 2942 for (int i=0; i<mCreatedMenus.size(); i++) { 2943 Fragment f = mCreatedMenus.get(i); 2944 if (newMenus == null || !newMenus.contains(f)) { 2945 f.onDestroyOptionsMenu(); 2946 } 2947 } 2948 } 2949 2950 mCreatedMenus = newMenus; 2951 2952 return show; 2953 } 2954 2955 public boolean dispatchPrepareOptionsMenu(Menu menu) { 2956 boolean show = false; 2957 if (mAdded != null) { 2958 for (int i=0; i<mAdded.size(); i++) { 2959 Fragment f = mAdded.get(i); 2960 if (f != null) { 2961 if (f.performPrepareOptionsMenu(menu)) { 2962 show = true; 2963 } 2964 } 2965 } 2966 } 2967 return show; 2968 } 2969 2970 public boolean dispatchOptionsItemSelected(MenuItem item) { 2971 if (mAdded != null) { 2972 for (int i=0; i<mAdded.size(); i++) { 2973 Fragment f = mAdded.get(i); 2974 if (f != null) { 2975 if (f.performOptionsItemSelected(item)) { 2976 return true; 2977 } 2978 } 2979 } 2980 } 2981 return false; 2982 } 2983 2984 public boolean dispatchContextItemSelected(MenuItem item) { 2985 if (mAdded != null) { 2986 for (int i=0; i<mAdded.size(); i++) { 2987 Fragment f = mAdded.get(i); 2988 if (f != null) { 2989 if (f.performContextItemSelected(item)) { 2990 return true; 2991 } 2992 } 2993 } 2994 } 2995 return false; 2996 } 2997 2998 public void dispatchOptionsMenuClosed(Menu menu) { 2999 if (mAdded != null) { 3000 for (int i=0; i<mAdded.size(); i++) { 3001 Fragment f = mAdded.get(i); 3002 if (f != null) { 3003 f.performOptionsMenuClosed(menu); 3004 } 3005 } 3006 } 3007 } 3008 3009 public void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb, 3010 boolean recursive) { 3011 if (mLifecycleCallbacks == null) { 3012 mLifecycleCallbacks = new CopyOnWriteArrayList<>(); 3013 } 3014 mLifecycleCallbacks.add(new Pair(cb, recursive)); 3015 } 3016 3017 public void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb) { 3018 if (mLifecycleCallbacks == null) { 3019 return; 3020 } 3021 3022 synchronized (mLifecycleCallbacks) { 3023 for (int i = 0, N = mLifecycleCallbacks.size(); i < N; i++) { 3024 if (mLifecycleCallbacks.get(i).first == cb) { 3025 mLifecycleCallbacks.remove(i); 3026 break; 3027 } 3028 } 3029 } 3030 } 3031 3032 void dispatchOnFragmentPreAttached(Fragment f, Context context, boolean onlyRecursive) { 3033 if (mParent != null) { 3034 FragmentManager parentManager = mParent.getFragmentManager(); 3035 if (parentManager instanceof FragmentManagerImpl) { 3036 ((FragmentManagerImpl) parentManager) 3037 .dispatchOnFragmentPreAttached(f, context, true); 3038 } 3039 } 3040 if (mLifecycleCallbacks == null) { 3041 return; 3042 } 3043 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3044 if (!onlyRecursive || p.second) { 3045 p.first.onFragmentPreAttached(this, f, context); 3046 } 3047 } 3048 } 3049 3050 void dispatchOnFragmentAttached(Fragment f, Context context, boolean onlyRecursive) { 3051 if (mParent != null) { 3052 FragmentManager parentManager = mParent.getFragmentManager(); 3053 if (parentManager instanceof FragmentManagerImpl) { 3054 ((FragmentManagerImpl) parentManager) 3055 .dispatchOnFragmentAttached(f, context, true); 3056 } 3057 } 3058 if (mLifecycleCallbacks == null) { 3059 return; 3060 } 3061 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3062 if (!onlyRecursive || p.second) { 3063 p.first.onFragmentAttached(this, f, context); 3064 } 3065 } 3066 } 3067 3068 void dispatchOnFragmentCreated(Fragment f, Bundle savedInstanceState, boolean onlyRecursive) { 3069 if (mParent != null) { 3070 FragmentManager parentManager = mParent.getFragmentManager(); 3071 if (parentManager instanceof FragmentManagerImpl) { 3072 ((FragmentManagerImpl) parentManager) 3073 .dispatchOnFragmentCreated(f, savedInstanceState, true); 3074 } 3075 } 3076 if (mLifecycleCallbacks == null) { 3077 return; 3078 } 3079 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3080 if (!onlyRecursive || p.second) { 3081 p.first.onFragmentCreated(this, f, savedInstanceState); 3082 } 3083 } 3084 } 3085 3086 void dispatchOnFragmentActivityCreated(Fragment f, Bundle savedInstanceState, 3087 boolean onlyRecursive) { 3088 if (mParent != null) { 3089 FragmentManager parentManager = mParent.getFragmentManager(); 3090 if (parentManager instanceof FragmentManagerImpl) { 3091 ((FragmentManagerImpl) parentManager) 3092 .dispatchOnFragmentActivityCreated(f, savedInstanceState, true); 3093 } 3094 } 3095 if (mLifecycleCallbacks == null) { 3096 return; 3097 } 3098 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3099 if (!onlyRecursive || p.second) { 3100 p.first.onFragmentActivityCreated(this, f, savedInstanceState); 3101 } 3102 } 3103 } 3104 3105 void dispatchOnFragmentViewCreated(Fragment f, View v, Bundle savedInstanceState, 3106 boolean onlyRecursive) { 3107 if (mParent != null) { 3108 FragmentManager parentManager = mParent.getFragmentManager(); 3109 if (parentManager instanceof FragmentManagerImpl) { 3110 ((FragmentManagerImpl) parentManager) 3111 .dispatchOnFragmentViewCreated(f, v, savedInstanceState, true); 3112 } 3113 } 3114 if (mLifecycleCallbacks == null) { 3115 return; 3116 } 3117 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3118 if (!onlyRecursive || p.second) { 3119 p.first.onFragmentViewCreated(this, f, v, savedInstanceState); 3120 } 3121 } 3122 } 3123 3124 void dispatchOnFragmentStarted(Fragment f, boolean onlyRecursive) { 3125 if (mParent != null) { 3126 FragmentManager parentManager = mParent.getFragmentManager(); 3127 if (parentManager instanceof FragmentManagerImpl) { 3128 ((FragmentManagerImpl) parentManager) 3129 .dispatchOnFragmentStarted(f, true); 3130 } 3131 } 3132 if (mLifecycleCallbacks == null) { 3133 return; 3134 } 3135 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3136 if (!onlyRecursive || p.second) { 3137 p.first.onFragmentStarted(this, f); 3138 } 3139 } 3140 } 3141 3142 void dispatchOnFragmentResumed(Fragment f, boolean onlyRecursive) { 3143 if (mParent != null) { 3144 FragmentManager parentManager = mParent.getFragmentManager(); 3145 if (parentManager instanceof FragmentManagerImpl) { 3146 ((FragmentManagerImpl) parentManager) 3147 .dispatchOnFragmentResumed(f, true); 3148 } 3149 } 3150 if (mLifecycleCallbacks == null) { 3151 return; 3152 } 3153 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3154 if (!onlyRecursive || p.second) { 3155 p.first.onFragmentResumed(this, f); 3156 } 3157 } 3158 } 3159 3160 void dispatchOnFragmentPaused(Fragment f, boolean onlyRecursive) { 3161 if (mParent != null) { 3162 FragmentManager parentManager = mParent.getFragmentManager(); 3163 if (parentManager instanceof FragmentManagerImpl) { 3164 ((FragmentManagerImpl) parentManager) 3165 .dispatchOnFragmentPaused(f, true); 3166 } 3167 } 3168 if (mLifecycleCallbacks == null) { 3169 return; 3170 } 3171 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3172 if (!onlyRecursive || p.second) { 3173 p.first.onFragmentPaused(this, f); 3174 } 3175 } 3176 } 3177 3178 void dispatchOnFragmentStopped(Fragment f, boolean onlyRecursive) { 3179 if (mParent != null) { 3180 FragmentManager parentManager = mParent.getFragmentManager(); 3181 if (parentManager instanceof FragmentManagerImpl) { 3182 ((FragmentManagerImpl) parentManager) 3183 .dispatchOnFragmentStopped(f, true); 3184 } 3185 } 3186 if (mLifecycleCallbacks == null) { 3187 return; 3188 } 3189 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3190 if (!onlyRecursive || p.second) { 3191 p.first.onFragmentStopped(this, f); 3192 } 3193 } 3194 } 3195 3196 void dispatchOnFragmentSaveInstanceState(Fragment f, Bundle outState, boolean onlyRecursive) { 3197 if (mParent != null) { 3198 FragmentManager parentManager = mParent.getFragmentManager(); 3199 if (parentManager instanceof FragmentManagerImpl) { 3200 ((FragmentManagerImpl) parentManager) 3201 .dispatchOnFragmentSaveInstanceState(f, outState, true); 3202 } 3203 } 3204 if (mLifecycleCallbacks == null) { 3205 return; 3206 } 3207 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3208 if (!onlyRecursive || p.second) { 3209 p.first.onFragmentSaveInstanceState(this, f, outState); 3210 } 3211 } 3212 } 3213 3214 void dispatchOnFragmentViewDestroyed(Fragment f, boolean onlyRecursive) { 3215 if (mParent != null) { 3216 FragmentManager parentManager = mParent.getFragmentManager(); 3217 if (parentManager instanceof FragmentManagerImpl) { 3218 ((FragmentManagerImpl) parentManager) 3219 .dispatchOnFragmentViewDestroyed(f, true); 3220 } 3221 } 3222 if (mLifecycleCallbacks == null) { 3223 return; 3224 } 3225 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3226 if (!onlyRecursive || p.second) { 3227 p.first.onFragmentViewDestroyed(this, f); 3228 } 3229 } 3230 } 3231 3232 void dispatchOnFragmentDestroyed(Fragment f, boolean onlyRecursive) { 3233 if (mParent != null) { 3234 FragmentManager parentManager = mParent.getFragmentManager(); 3235 if (parentManager instanceof FragmentManagerImpl) { 3236 ((FragmentManagerImpl) parentManager) 3237 .dispatchOnFragmentDestroyed(f, true); 3238 } 3239 } 3240 if (mLifecycleCallbacks == null) { 3241 return; 3242 } 3243 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3244 if (!onlyRecursive || p.second) { 3245 p.first.onFragmentDestroyed(this, f); 3246 } 3247 } 3248 } 3249 3250 void dispatchOnFragmentDetached(Fragment f, boolean onlyRecursive) { 3251 if (mParent != null) { 3252 FragmentManager parentManager = mParent.getFragmentManager(); 3253 if (parentManager instanceof FragmentManagerImpl) { 3254 ((FragmentManagerImpl) parentManager) 3255 .dispatchOnFragmentDetached(f, true); 3256 } 3257 } 3258 if (mLifecycleCallbacks == null) { 3259 return; 3260 } 3261 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3262 if (!onlyRecursive || p.second) { 3263 p.first.onFragmentDetached(this, f); 3264 } 3265 } 3266 } 3267 3268 public static int reverseTransit(int transit) { 3269 int rev = 0; 3270 switch (transit) { 3271 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 3272 rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; 3273 break; 3274 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 3275 rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN; 3276 break; 3277 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 3278 rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE; 3279 break; 3280 } 3281 return rev; 3282 3283 } 3284 3285 public static final int ANIM_STYLE_OPEN_ENTER = 1; 3286 public static final int ANIM_STYLE_OPEN_EXIT = 2; 3287 public static final int ANIM_STYLE_CLOSE_ENTER = 3; 3288 public static final int ANIM_STYLE_CLOSE_EXIT = 4; 3289 public static final int ANIM_STYLE_FADE_ENTER = 5; 3290 public static final int ANIM_STYLE_FADE_EXIT = 6; 3291 3292 public static int transitToStyleIndex(int transit, boolean enter) { 3293 int animAttr = -1; 3294 switch (transit) { 3295 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 3296 animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT; 3297 break; 3298 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 3299 animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT; 3300 break; 3301 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 3302 animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT; 3303 break; 3304 } 3305 return animAttr; 3306 } 3307 3308 @Override 3309 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { 3310 if (!"fragment".equals(name)) { 3311 return null; 3312 } 3313 3314 String fname = attrs.getAttributeValue(null, "class"); 3315 TypedArray a = context.obtainStyledAttributes(attrs, FragmentTag.Fragment); 3316 if (fname == null) { 3317 fname = a.getString(FragmentTag.Fragment_name); 3318 } 3319 int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID); 3320 String tag = a.getString(FragmentTag.Fragment_tag); 3321 a.recycle(); 3322 3323 if (!Fragment.isSupportFragmentClass(mHost.getContext(), fname)) { 3324 // Invalid support lib fragment; let the device's framework handle it. 3325 // This will allow android.app.Fragments to do the right thing. 3326 return null; 3327 } 3328 3329 int containerId = parent != null ? parent.getId() : 0; 3330 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) { 3331 throw new IllegalArgumentException(attrs.getPositionDescription() 3332 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname); 3333 } 3334 3335 // If we restored from a previous state, we may already have 3336 // instantiated this fragment from the state and should use 3337 // that instance instead of making a new one. 3338 Fragment fragment = id != View.NO_ID ? findFragmentById(id) : null; 3339 if (fragment == null && tag != null) { 3340 fragment = findFragmentByTag(tag); 3341 } 3342 if (fragment == null && containerId != View.NO_ID) { 3343 fragment = findFragmentById(containerId); 3344 } 3345 3346 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x" 3347 + Integer.toHexString(id) + " fname=" + fname 3348 + " existing=" + fragment); 3349 if (fragment == null) { 3350 fragment = Fragment.instantiate(context, fname); 3351 fragment.mFromLayout = true; 3352 fragment.mFragmentId = id != 0 ? id : containerId; 3353 fragment.mContainerId = containerId; 3354 fragment.mTag = tag; 3355 fragment.mInLayout = true; 3356 fragment.mFragmentManager = this; 3357 fragment.mHost = mHost; 3358 fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState); 3359 addFragment(fragment, true); 3360 3361 } else if (fragment.mInLayout) { 3362 // A fragment already exists and it is not one we restored from 3363 // previous state. 3364 throw new IllegalArgumentException(attrs.getPositionDescription() 3365 + ": Duplicate id 0x" + Integer.toHexString(id) 3366 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId) 3367 + " with another fragment for " + fname); 3368 } else { 3369 // This fragment was retained from a previous instance; get it 3370 // going now. 3371 fragment.mInLayout = true; 3372 fragment.mHost = mHost; 3373 // If this fragment is newly instantiated (either right now, or 3374 // from last saved state), then give it the attributes to 3375 // initialize itself. 3376 if (!fragment.mRetaining) { 3377 fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState); 3378 } 3379 } 3380 3381 // If we haven't finished entering the CREATED state ourselves yet, 3382 // push the inflated child fragment along. 3383 if (mCurState < Fragment.CREATED && fragment.mFromLayout) { 3384 moveToState(fragment, Fragment.CREATED, 0, 0, false); 3385 } else { 3386 moveToState(fragment); 3387 } 3388 3389 if (fragment.mView == null) { 3390 throw new IllegalStateException("Fragment " + fname 3391 + " did not create a view."); 3392 } 3393 if (id != 0) { 3394 fragment.mView.setId(id); 3395 } 3396 if (fragment.mView.getTag() == null) { 3397 fragment.mView.setTag(tag); 3398 } 3399 return fragment.mView; 3400 } 3401 3402 LayoutInflaterFactory getLayoutInflaterFactory() { 3403 return this; 3404 } 3405 3406 static class FragmentTag { 3407 public static final int[] Fragment = { 3408 0x01010003, 0x010100d0, 0x010100d1 3409 }; 3410 public static final int Fragment_id = 1; 3411 public static final int Fragment_name = 0; 3412 public static final int Fragment_tag = 2; 3413 } 3414 3415 /** 3416 * An add or pop transaction to be scheduled for the UI thread. 3417 */ 3418 interface OpGenerator { 3419 /** 3420 * Generate transactions to add to {@code records} and whether or not the transaction is 3421 * an add or pop to {@code isRecordPop}. 3422 * 3423 * records and isRecordPop must be added equally so that each transaction in records 3424 * matches the boolean for whether or not it is a pop in isRecordPop. 3425 * 3426 * @param records A list to add transactions to. 3427 * @param isRecordPop A list to add whether or not the transactions added to records is 3428 * a pop transaction. 3429 * @return true if something was added or false otherwise. 3430 */ 3431 boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop); 3432 } 3433 3434 /** 3435 * A pop operation OpGenerator. This will be run on the UI thread and will generate the 3436 * transactions that will be popped if anything can be popped. 3437 */ 3438 private class PopBackStackState implements OpGenerator { 3439 final String mName; 3440 final int mId; 3441 final int mFlags; 3442 3443 PopBackStackState(String name, int id, int flags) { 3444 mName = name; 3445 mId = id; 3446 mFlags = flags; 3447 } 3448 3449 @Override 3450 public boolean generateOps(ArrayList<BackStackRecord> records, 3451 ArrayList<Boolean> isRecordPop) { 3452 return popBackStackState(records, isRecordPop, mName, mId, mFlags); 3453 } 3454 } 3455 3456 /** 3457 * A listener for a postponed transaction. This waits until 3458 * {@link Fragment#startPostponedEnterTransition()} is called or a transaction is started 3459 * that interacts with this one, based on interactions with the fragment container. 3460 */ 3461 static class StartEnterTransitionListener 3462 implements Fragment.OnStartEnterTransitionListener { 3463 private final boolean mIsBack; 3464 private final BackStackRecord mRecord; 3465 private int mNumPostponed; 3466 3467 StartEnterTransitionListener(BackStackRecord record, boolean isBack) { 3468 mIsBack = isBack; 3469 mRecord = record; 3470 } 3471 3472 /** 3473 * Called from {@link Fragment#startPostponedEnterTransition()}, this decreases the 3474 * number of Fragments that are postponed. This may cause the transaction to schedule 3475 * to finish running and run transitions and animations. 3476 */ 3477 @Override 3478 public void onStartEnterTransition() { 3479 mNumPostponed--; 3480 if (mNumPostponed != 0) { 3481 return; 3482 } 3483 mRecord.mManager.scheduleCommit(); 3484 } 3485 3486 /** 3487 * Called from {@link Fragment# 3488 * setOnStartEnterTransitionListener(Fragment.OnStartEnterTransitionListener)}, this 3489 * increases the number of fragments that are postponed as part of this transaction. 3490 */ 3491 @Override 3492 public void startListening() { 3493 mNumPostponed++; 3494 } 3495 3496 /** 3497 * @return true if there are no more postponed fragments as part of the transaction. 3498 */ 3499 public boolean isReady() { 3500 return mNumPostponed == 0; 3501 } 3502 3503 /** 3504 * Completes the transaction and start the animations and transitions. This may skip 3505 * the transitions if this is called before all fragments have called 3506 * {@link Fragment#startPostponedEnterTransition()}. 3507 */ 3508 public void completeTransaction() { 3509 final boolean canceled; 3510 canceled = mNumPostponed > 0; 3511 FragmentManagerImpl manager = mRecord.mManager; 3512 final int numAdded = manager.mAdded.size(); 3513 for (int i = 0; i < numAdded; i++) { 3514 final Fragment fragment = manager.mAdded.get(i); 3515 fragment.setOnStartEnterTransitionListener(null); 3516 if (canceled && fragment.isPostponed()) { 3517 fragment.startPostponedEnterTransition(); 3518 } 3519 } 3520 mRecord.mManager.completeExecute(mRecord, mIsBack, !canceled, true); 3521 } 3522 3523 /** 3524 * Cancels this transaction instead of completing it. That means that the state isn't 3525 * changed, so the pop results in no change to the state. 3526 */ 3527 public void cancelTransaction() { 3528 mRecord.mManager.completeExecute(mRecord, mIsBack, false, false); 3529 } 3530 } 3531} 3532