FragmentManager.java revision 8e10080c914d1ad0784394fa3026b85535535847
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 f.mIsNewlyAdded = true; 1310 } 1311 if (f.mHidden) { 1312 f.mView.setVisibility(View.GONE); 1313 f.mIsNewlyAdded = false; // No animation 1314 } 1315 f.onViewCreated(f.mView, f.mSavedFragmentState); 1316 dispatchOnFragmentViewCreated(f, f.mView, f.mSavedFragmentState, 1317 false); 1318 } else { 1319 f.mInnerView = null; 1320 } 1321 } 1322 1323 f.performActivityCreated(f.mSavedFragmentState); 1324 dispatchOnFragmentActivityCreated(f, f.mSavedFragmentState, false); 1325 if (f.mView != null) { 1326 f.restoreViewState(f.mSavedFragmentState); 1327 } 1328 f.mSavedFragmentState = null; 1329 } 1330 case Fragment.ACTIVITY_CREATED: 1331 if (newState > Fragment.ACTIVITY_CREATED) { 1332 f.mState = Fragment.STOPPED; 1333 } 1334 case Fragment.STOPPED: 1335 if (newState > Fragment.STOPPED) { 1336 if (DEBUG) Log.v(TAG, "moveto STARTED: " + f); 1337 f.performStart(); 1338 dispatchOnFragmentStarted(f, false); 1339 } 1340 case Fragment.STARTED: 1341 if (newState > Fragment.STARTED) { 1342 if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f); 1343 f.performResume(); 1344 dispatchOnFragmentResumed(f, false); 1345 f.mSavedFragmentState = null; 1346 f.mSavedViewState = null; 1347 } 1348 } 1349 } else if (f.mState > newState) { 1350 switch (f.mState) { 1351 case Fragment.RESUMED: 1352 if (newState < Fragment.RESUMED) { 1353 if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f); 1354 f.performPause(); 1355 dispatchOnFragmentPaused(f, false); 1356 } 1357 case Fragment.STARTED: 1358 if (newState < Fragment.STARTED) { 1359 if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f); 1360 f.performStop(); 1361 dispatchOnFragmentStopped(f, false); 1362 } 1363 case Fragment.STOPPED: 1364 if (newState < Fragment.STOPPED) { 1365 if (DEBUG) Log.v(TAG, "movefrom STOPPED: " + f); 1366 f.performReallyStop(); 1367 } 1368 case Fragment.ACTIVITY_CREATED: 1369 if (newState < Fragment.ACTIVITY_CREATED) { 1370 if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f); 1371 if (f.mView != null) { 1372 // Need to save the current view state if not 1373 // done already. 1374 if (mHost.onShouldSaveFragmentState(f) && f.mSavedViewState == null) { 1375 saveFragmentViewState(f); 1376 } 1377 } 1378 f.performDestroyView(); 1379 dispatchOnFragmentViewDestroyed(f, false); 1380 if (f.mView != null && f.mContainer != null) { 1381 Animation anim = null; 1382 if (mCurState > Fragment.INITIALIZING && !mDestroyed 1383 && f.mView.getVisibility() == View.VISIBLE) { 1384 anim = loadAnimation(f, transit, false, 1385 transitionStyle); 1386 } 1387 if (anim != null) { 1388 final Fragment fragment = f; 1389 f.setAnimatingAway(f.mView); 1390 f.setStateAfterAnimating(newState); 1391 final View viewToAnimate = f.mView; 1392 anim.setAnimationListener(new AnimateOnHWLayerIfNeededListener( 1393 viewToAnimate, anim) { 1394 @Override 1395 public void onAnimationEnd(Animation animation) { 1396 super.onAnimationEnd(animation); 1397 if (fragment.getAnimatingAway() != null) { 1398 fragment.setAnimatingAway(null); 1399 moveToState(fragment, fragment.getStateAfterAnimating(), 1400 0, 0, false); 1401 } 1402 } 1403 }); 1404 f.mView.startAnimation(anim); 1405 } 1406 f.mContainer.removeView(f.mView); 1407 } 1408 f.mContainer = null; 1409 f.mView = null; 1410 f.mInnerView = null; 1411 } 1412 case Fragment.CREATED: 1413 if (newState < Fragment.CREATED) { 1414 if (mDestroyed) { 1415 if (f.getAnimatingAway() != null) { 1416 // The fragment's containing activity is 1417 // being destroyed, but this fragment is 1418 // currently animating away. Stop the 1419 // animation right now -- it is not needed, 1420 // and we can't wait any more on destroying 1421 // the fragment. 1422 View v = f.getAnimatingAway(); 1423 f.setAnimatingAway(null); 1424 v.clearAnimation(); 1425 } 1426 } 1427 if (f.getAnimatingAway() != null) { 1428 // We are waiting for the fragment's view to finish 1429 // animating away. Just make a note of the state 1430 // the fragment now should move to once the animation 1431 // is done. 1432 f.setStateAfterAnimating(newState); 1433 newState = Fragment.CREATED; 1434 } else { 1435 if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f); 1436 if (!f.mRetaining) { 1437 f.performDestroy(); 1438 dispatchOnFragmentDestroyed(f, false); 1439 } else { 1440 f.mState = Fragment.INITIALIZING; 1441 } 1442 1443 f.performDetach(); 1444 dispatchOnFragmentDetached(f, false); 1445 if (!keepActive) { 1446 if (!f.mRetaining) { 1447 makeInactive(f); 1448 } else { 1449 f.mHost = null; 1450 f.mParentFragment = null; 1451 f.mFragmentManager = null; 1452 } 1453 } 1454 } 1455 } 1456 } 1457 } 1458 1459 if (f.mState != newState) { 1460 Log.w(TAG, "moveToState: Fragment state for " + f + " not updated inline; " 1461 + "expected state " + newState + " found " + f.mState); 1462 f.mState = newState; 1463 } 1464 } 1465 1466 void moveToState(Fragment f) { 1467 moveToState(f, mCurState, 0, 0, false); 1468 } 1469 1470 /** 1471 * Fragments that have been shown or hidden don't have their visibility changed or 1472 * animations run during the {@link #showFragment(Fragment)} or {@link #hideFragment(Fragment)} 1473 * calls. After fragments are brought to their final state in 1474 * {@link #moveFragmentToExpectedState(Fragment)} the fragments that have been shown or 1475 * hidden must have their visibility changed and their animations started here. 1476 * 1477 * @param fragment The fragment with mHiddenChanged = true that should change its View's 1478 * visibility and start the show or hide animation. 1479 */ 1480 void completeShowHideFragment(final Fragment fragment) { 1481 if (fragment.mView != null) { 1482 Animation anim = loadAnimation(fragment, fragment.getNextTransition(), 1483 !fragment.mHidden, fragment.getNextTransitionStyle()); 1484 if (anim != null) { 1485 setHWLayerAnimListenerIfAlpha(fragment.mView, anim); 1486 fragment.mView.startAnimation(anim); 1487 setHWLayerAnimListenerIfAlpha(fragment.mView, anim); 1488 anim.start(); 1489 } 1490 final int visibility = fragment.mHidden && !fragment.isHideReplaced() 1491 ? View.GONE 1492 : View.VISIBLE; 1493 fragment.mView.setVisibility(visibility); 1494 if (fragment.isHideReplaced()) { 1495 fragment.setHideReplaced(false); 1496 } 1497 } 1498 if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) { 1499 mNeedMenuInvalidate = true; 1500 } 1501 fragment.mHiddenChanged = false; 1502 fragment.onHiddenChanged(fragment.mHidden); 1503 } 1504 1505 /** 1506 * Moves a fragment to its expected final state or the fragment manager's state, depending 1507 * on whether the fragment manager's state is raised properly. 1508 * 1509 * @param f The fragment to change. 1510 */ 1511 void moveFragmentToExpectedState(Fragment f) { 1512 if (f == null) { 1513 return; 1514 } 1515 int nextState = mCurState; 1516 if (f.mRemoving) { 1517 if (f.isInBackStack()) { 1518 nextState = Math.min(nextState, Fragment.CREATED); 1519 } else { 1520 nextState = Math.min(nextState, Fragment.INITIALIZING); 1521 } 1522 } 1523 moveToState(f, nextState, f.getNextTransition(), f.getNextTransitionStyle(), false); 1524 1525 if (f.mView != null) { 1526 // Move the view if it is out of order 1527 Fragment underFragment = findFragmentUnder(f); 1528 if (underFragment != null) { 1529 final View underView = underFragment.mView; 1530 // make sure this fragment is in the right order. 1531 final ViewGroup container = f.mContainer; 1532 int underIndex = container.indexOfChild(underView); 1533 int viewIndex = container.indexOfChild(f.mView); 1534 if (viewIndex < underIndex) { 1535 container.removeViewAt(viewIndex); 1536 container.addView(f.mView, underIndex); 1537 } 1538 } 1539 if (f.mIsNewlyAdded && f.mContainer != null) { 1540 // Make it visible and run the animations 1541 f.mView.setVisibility(View.VISIBLE); 1542 f.mIsNewlyAdded = false; 1543 // run animations: 1544 Animation anim = loadAnimation(f, f.getNextTransition(), true, 1545 f.getNextTransitionStyle()); 1546 if (anim != null) { 1547 setHWLayerAnimListenerIfAlpha(f.mView, anim); 1548 f.mView.startAnimation(anim); 1549 } 1550 } 1551 } 1552 if (f.mHiddenChanged) { 1553 completeShowHideFragment(f); 1554 } 1555 } 1556 1557 /** 1558 * Changes the state of the fragment manager to {@code newState}. If the fragment manager 1559 * changes state or {@code always} is {@code true}, any fragments within it have their 1560 * states updated as well. 1561 * 1562 * @param newState The new state for the fragment manager 1563 * @param always If {@code true}, all fragments update their state, even 1564 * if {@code newState} matches the current fragment manager's state. 1565 */ 1566 void moveToState(int newState, boolean always) { 1567 if (mHost == null && newState != Fragment.INITIALIZING) { 1568 throw new IllegalStateException("No activity"); 1569 } 1570 1571 if (!always && newState == mCurState) { 1572 return; 1573 } 1574 1575 mCurState = newState; 1576 1577 if (mActive != null) { 1578 boolean loadersRunning = false; 1579 1580 // Must add them in the proper order. mActive fragments may be out of order 1581 if (mAdded != null) { 1582 final int numAdded = mAdded.size(); 1583 for (int i = 0; i < numAdded; i++) { 1584 Fragment f = mAdded.get(i); 1585 moveFragmentToExpectedState(f); 1586 if (f.mLoaderManager != null) { 1587 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 1588 } 1589 } 1590 } 1591 1592 // Now iterate through all active fragments. These will include those that are removed 1593 // and detached. 1594 final int numActive = mActive.size(); 1595 for (int i = 0; i < numActive; i++) { 1596 Fragment f = mActive.get(i); 1597 if (f != null && (f.mRemoving || f.mDetached) && !f.mIsNewlyAdded) { 1598 moveFragmentToExpectedState(f); 1599 if (f.mLoaderManager != null) { 1600 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 1601 } 1602 } 1603 } 1604 1605 if (!loadersRunning) { 1606 startPendingDeferredFragments(); 1607 } 1608 1609 if (mNeedMenuInvalidate && mHost != null && mCurState == Fragment.RESUMED) { 1610 mHost.onSupportInvalidateOptionsMenu(); 1611 mNeedMenuInvalidate = false; 1612 } 1613 } 1614 } 1615 1616 void startPendingDeferredFragments() { 1617 if (mActive == null) return; 1618 1619 for (int i=0; i<mActive.size(); i++) { 1620 Fragment f = mActive.get(i); 1621 if (f != null) { 1622 performPendingDeferredStart(f); 1623 } 1624 } 1625 } 1626 1627 void makeActive(Fragment f) { 1628 if (f.mIndex >= 0) { 1629 return; 1630 } 1631 1632 if (mAvailIndices == null || mAvailIndices.size() <= 0) { 1633 if (mActive == null) { 1634 mActive = new ArrayList<Fragment>(); 1635 } 1636 f.setIndex(mActive.size(), mParent); 1637 mActive.add(f); 1638 1639 } else { 1640 f.setIndex(mAvailIndices.remove(mAvailIndices.size()-1), mParent); 1641 mActive.set(f.mIndex, f); 1642 } 1643 if (DEBUG) Log.v(TAG, "Allocated fragment index " + f); 1644 } 1645 1646 void makeInactive(Fragment f) { 1647 if (f.mIndex < 0) { 1648 return; 1649 } 1650 1651 if (DEBUG) Log.v(TAG, "Freeing fragment index " + f); 1652 mActive.set(f.mIndex, null); 1653 if (mAvailIndices == null) { 1654 mAvailIndices = new ArrayList<Integer>(); 1655 } 1656 mAvailIndices.add(f.mIndex); 1657 mHost.inactivateFragment(f.mWho); 1658 f.initState(); 1659 } 1660 1661 public void addFragment(Fragment fragment, boolean moveToStateNow) { 1662 if (mAdded == null) { 1663 mAdded = new ArrayList<Fragment>(); 1664 } 1665 if (DEBUG) Log.v(TAG, "add: " + fragment); 1666 makeActive(fragment); 1667 if (!fragment.mDetached) { 1668 if (mAdded.contains(fragment)) { 1669 throw new IllegalStateException("Fragment already added: " + fragment); 1670 } 1671 mAdded.add(fragment); 1672 fragment.mAdded = true; 1673 fragment.mRemoving = false; 1674 if (fragment.mView == null) { 1675 fragment.mHiddenChanged = false; 1676 } 1677 if (fragment.mHasMenu && fragment.mMenuVisible) { 1678 mNeedMenuInvalidate = true; 1679 } 1680 if (moveToStateNow) { 1681 moveToState(fragment); 1682 } 1683 } 1684 } 1685 1686 public void removeFragment(Fragment fragment) { 1687 if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); 1688 final boolean inactive = !fragment.isInBackStack(); 1689 if (!fragment.mDetached || inactive) { 1690 if (mAdded != null) { 1691 mAdded.remove(fragment); 1692 } 1693 if (fragment.mHasMenu && fragment.mMenuVisible) { 1694 mNeedMenuInvalidate = true; 1695 } 1696 fragment.mAdded = false; 1697 fragment.mRemoving = true; 1698 } 1699 } 1700 1701 /** 1702 * Marks a fragment as hidden to be later animated in with 1703 * {@link #completeShowHideFragment(Fragment)}. 1704 * 1705 * @param fragment The fragment to be shown. 1706 */ 1707 public void hideFragment(Fragment fragment) { 1708 if (DEBUG) Log.v(TAG, "hide: " + fragment); 1709 if (!fragment.mHidden) { 1710 fragment.mHidden = true; 1711 // Toggle hidden changed so that if a fragment goes through show/hide/show 1712 // it doesn't go through the animation. 1713 fragment.mHiddenChanged = !fragment.mHiddenChanged; 1714 } 1715 } 1716 1717 /** 1718 * Marks a fragment as shown to be later animated in with 1719 * {@link #completeShowHideFragment(Fragment)}. 1720 * 1721 * @param fragment The fragment to be shown. 1722 */ 1723 public void showFragment(Fragment fragment) { 1724 if (DEBUG) Log.v(TAG, "show: " + fragment); 1725 if (fragment.mHidden) { 1726 fragment.mHidden = false; 1727 // Toggle hidden changed so that if a fragment goes through show/hide/show 1728 // it doesn't go through the animation. 1729 fragment.mHiddenChanged = !fragment.mHiddenChanged; 1730 } 1731 } 1732 1733 public void detachFragment(Fragment fragment) { 1734 if (DEBUG) Log.v(TAG, "detach: " + fragment); 1735 if (!fragment.mDetached) { 1736 fragment.mDetached = true; 1737 if (fragment.mAdded) { 1738 // We are not already in back stack, so need to remove the fragment. 1739 if (mAdded != null) { 1740 if (DEBUG) Log.v(TAG, "remove from detach: " + fragment); 1741 mAdded.remove(fragment); 1742 } 1743 if (fragment.mHasMenu && fragment.mMenuVisible) { 1744 mNeedMenuInvalidate = true; 1745 } 1746 fragment.mAdded = false; 1747 } 1748 } 1749 } 1750 1751 public void attachFragment(Fragment fragment) { 1752 if (DEBUG) Log.v(TAG, "attach: " + fragment); 1753 if (fragment.mDetached) { 1754 fragment.mDetached = false; 1755 if (!fragment.mAdded) { 1756 if (mAdded == null) { 1757 mAdded = new ArrayList<Fragment>(); 1758 } 1759 if (mAdded.contains(fragment)) { 1760 throw new IllegalStateException("Fragment already added: " + fragment); 1761 } 1762 if (DEBUG) Log.v(TAG, "add from attach: " + fragment); 1763 mAdded.add(fragment); 1764 fragment.mAdded = true; 1765 if (fragment.mHasMenu && fragment.mMenuVisible) { 1766 mNeedMenuInvalidate = true; 1767 } 1768 } 1769 } 1770 } 1771 1772 @Override 1773 public Fragment findFragmentById(int id) { 1774 if (mAdded != null) { 1775 // First look through added fragments. 1776 for (int i=mAdded.size()-1; i>=0; i--) { 1777 Fragment f = mAdded.get(i); 1778 if (f != null && f.mFragmentId == id) { 1779 return f; 1780 } 1781 } 1782 } 1783 if (mActive != null) { 1784 // Now for any known fragment. 1785 for (int i=mActive.size()-1; i>=0; i--) { 1786 Fragment f = mActive.get(i); 1787 if (f != null && f.mFragmentId == id) { 1788 return f; 1789 } 1790 } 1791 } 1792 return null; 1793 } 1794 1795 @Override 1796 public Fragment findFragmentByTag(String tag) { 1797 if (mAdded != null && tag != null) { 1798 // First look through added fragments. 1799 for (int i=mAdded.size()-1; i>=0; i--) { 1800 Fragment f = mAdded.get(i); 1801 if (f != null && tag.equals(f.mTag)) { 1802 return f; 1803 } 1804 } 1805 } 1806 if (mActive != null && tag != null) { 1807 // Now for any known fragment. 1808 for (int i=mActive.size()-1; i>=0; i--) { 1809 Fragment f = mActive.get(i); 1810 if (f != null && tag.equals(f.mTag)) { 1811 return f; 1812 } 1813 } 1814 } 1815 return null; 1816 } 1817 1818 public Fragment findFragmentByWho(String who) { 1819 if (mActive != null && who != null) { 1820 for (int i=mActive.size()-1; i>=0; i--) { 1821 Fragment f = mActive.get(i); 1822 if (f != null && (f=f.findFragmentByWho(who)) != null) { 1823 return f; 1824 } 1825 } 1826 } 1827 return null; 1828 } 1829 1830 private void checkStateLoss() { 1831 if (mStateSaved) { 1832 throw new IllegalStateException( 1833 "Can not perform this action after onSaveInstanceState"); 1834 } 1835 if (mNoTransactionsBecause != null) { 1836 throw new IllegalStateException( 1837 "Can not perform this action inside of " + mNoTransactionsBecause); 1838 } 1839 } 1840 1841 /** 1842 * Adds an action to the queue of pending actions. 1843 * 1844 * @param action the action to add 1845 * @param allowStateLoss whether to allow loss of state information 1846 * @throws IllegalStateException if the activity has been destroyed 1847 */ 1848 public void enqueueAction(OpGenerator action, boolean allowStateLoss) { 1849 if (!allowStateLoss) { 1850 checkStateLoss(); 1851 } 1852 synchronized (this) { 1853 if (mDestroyed || mHost == null) { 1854 throw new IllegalStateException("Activity has been destroyed"); 1855 } 1856 if (mPendingActions == null) { 1857 mPendingActions = new ArrayList<>(); 1858 } 1859 mPendingActions.add(action); 1860 scheduleCommit(); 1861 } 1862 } 1863 1864 /** 1865 * Schedules the execution when one hasn't been scheduled already. This should happen 1866 * the first time {@link #enqueueAction(OpGenerator, boolean)} is called or when 1867 * a postponed transaction has been started with 1868 * {@link Fragment#startPostponedEnterTransition()} 1869 */ 1870 private void scheduleCommit() { 1871 synchronized (this) { 1872 boolean postponeReady = 1873 mPostponedTransactions != null && !mPostponedTransactions.isEmpty(); 1874 boolean pendingReady = mPendingActions != null && mPendingActions.size() == 1; 1875 if (postponeReady || pendingReady) { 1876 mHost.getHandler().removeCallbacks(mExecCommit); 1877 mHost.getHandler().post(mExecCommit); 1878 } 1879 } 1880 } 1881 1882 public int allocBackStackIndex(BackStackRecord bse) { 1883 synchronized (this) { 1884 if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) { 1885 if (mBackStackIndices == null) { 1886 mBackStackIndices = new ArrayList<BackStackRecord>(); 1887 } 1888 int index = mBackStackIndices.size(); 1889 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1890 mBackStackIndices.add(bse); 1891 return index; 1892 1893 } else { 1894 int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1); 1895 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1896 mBackStackIndices.set(index, bse); 1897 return index; 1898 } 1899 } 1900 } 1901 1902 public void setBackStackIndex(int index, BackStackRecord bse) { 1903 synchronized (this) { 1904 if (mBackStackIndices == null) { 1905 mBackStackIndices = new ArrayList<BackStackRecord>(); 1906 } 1907 int N = mBackStackIndices.size(); 1908 if (index < N) { 1909 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1910 mBackStackIndices.set(index, bse); 1911 } else { 1912 while (N < index) { 1913 mBackStackIndices.add(null); 1914 if (mAvailBackStackIndices == null) { 1915 mAvailBackStackIndices = new ArrayList<Integer>(); 1916 } 1917 if (DEBUG) Log.v(TAG, "Adding available back stack index " + N); 1918 mAvailBackStackIndices.add(N); 1919 N++; 1920 } 1921 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1922 mBackStackIndices.add(bse); 1923 } 1924 } 1925 } 1926 1927 public void freeBackStackIndex(int index) { 1928 synchronized (this) { 1929 mBackStackIndices.set(index, null); 1930 if (mAvailBackStackIndices == null) { 1931 mAvailBackStackIndices = new ArrayList<Integer>(); 1932 } 1933 if (DEBUG) Log.v(TAG, "Freeing back stack index " + index); 1934 mAvailBackStackIndices.add(index); 1935 } 1936 } 1937 1938 /** 1939 * Broken out from exec*, this prepares for gathering and executing operations. 1940 * 1941 * @param allowStateLoss true if state loss should be ignored or false if it should be 1942 * checked. 1943 */ 1944 private void ensureExecReady(boolean allowStateLoss) { 1945 if (mExecutingActions) { 1946 throw new IllegalStateException("FragmentManager is already executing transactions"); 1947 } 1948 1949 if (Looper.myLooper() != mHost.getHandler().getLooper()) { 1950 throw new IllegalStateException("Must be called from main thread of fragment host"); 1951 } 1952 1953 if (!allowStateLoss) { 1954 checkStateLoss(); 1955 } 1956 1957 if (mTmpRecords == null) { 1958 mTmpRecords = new ArrayList<>(); 1959 mTmpIsPop = new ArrayList<>(); 1960 } 1961 executePostponedTransaction(null, null); 1962 } 1963 1964 public void execSingleAction(OpGenerator action, boolean allowStateLoss) { 1965 ensureExecReady(allowStateLoss); 1966 if (action.generateOps(mTmpRecords, mTmpIsPop)) { 1967 mExecutingActions = true; 1968 try { 1969 optimizeAndExecuteOps(mTmpRecords, mTmpIsPop); 1970 } finally { 1971 cleanupExec(); 1972 } 1973 } 1974 1975 doPendingDeferredStart(); 1976 } 1977 1978 /** 1979 * Broken out of exec*, this cleans up the mExecutingActions and the temporary structures 1980 * used in executing operations. 1981 */ 1982 private void cleanupExec() { 1983 mExecutingActions = false; 1984 mTmpIsPop.clear(); 1985 mTmpRecords.clear(); 1986 } 1987 1988 /** 1989 * Only call from main thread! 1990 */ 1991 public boolean execPendingActions() { 1992 ensureExecReady(true); 1993 1994 boolean didSomething = false; 1995 while (generateOpsForPendingActions(mTmpRecords, mTmpIsPop)) { 1996 mExecutingActions = true; 1997 try { 1998 optimizeAndExecuteOps(mTmpRecords, mTmpIsPop); 1999 } finally { 2000 cleanupExec(); 2001 } 2002 didSomething = true; 2003 } 2004 2005 doPendingDeferredStart(); 2006 2007 return didSomething; 2008 } 2009 2010 /** 2011 * Complete the execution of transactions that have previously been postponed, but are 2012 * now ready. 2013 */ 2014 private void executePostponedTransaction(ArrayList<BackStackRecord> records, 2015 ArrayList<Boolean> isRecordPop) { 2016 int numPostponed = mPostponedTransactions == null ? 0 : mPostponedTransactions.size(); 2017 for (int i = 0; i < numPostponed; i++) { 2018 StartEnterTransitionListener listener = mPostponedTransactions.get(i); 2019 if (records != null && !listener.mIsBack) { 2020 int index = records.indexOf(listener.mRecord); 2021 if (index != -1 && isRecordPop.get(index)) { 2022 listener.cancelTransaction(); 2023 continue; 2024 } 2025 } 2026 if (listener.isReady() || (records != null 2027 && listener.mRecord.interactsWith(records, 0, records.size()))) { 2028 mPostponedTransactions.remove(i); 2029 i--; 2030 numPostponed--; 2031 int index; 2032 if (records != null && !listener.mIsBack 2033 && (index = records.indexOf(listener.mRecord)) != -1 2034 && isRecordPop.get(index)) { 2035 // This is popping a postponed transaction 2036 listener.cancelTransaction(); 2037 } else { 2038 listener.completeTransaction(); 2039 } 2040 } 2041 } 2042 } 2043 2044 /** 2045 * Optimizes BackStackRecord operations. This method merges operations of proximate records 2046 * that allow optimization. See {@link FragmentTransaction#setAllowOptimization(boolean)}. 2047 * <p> 2048 * For example, a transaction that adds to the back stack and then another that pops that 2049 * back stack record will be optimized. 2050 * <p> 2051 * Likewise, two transactions committed that are executed at the same time will be optimized 2052 * as well as two pop operations executed together. 2053 * 2054 * @param records The records pending execution 2055 * @param isRecordPop The direction that these records are being run. 2056 */ 2057 private void optimizeAndExecuteOps(ArrayList<BackStackRecord> records, 2058 ArrayList<Boolean> isRecordPop) { 2059 if (records == null || records.isEmpty()) { 2060 return; 2061 } 2062 2063 if (isRecordPop == null || records.size() != isRecordPop.size()) { 2064 throw new IllegalStateException("Internal error with the back stack records"); 2065 } 2066 2067 // Force start of any postponed transactions that interact with scheduled transactions: 2068 executePostponedTransaction(records, isRecordPop); 2069 2070 final int numRecords = records.size(); 2071 int startIndex = 0; 2072 for (int recordNum = 0; recordNum < numRecords; recordNum++) { 2073 final boolean canOptimize = records.get(recordNum).mAllowOptimization; 2074 if (!canOptimize) { 2075 // execute all previous transactions 2076 if (startIndex != recordNum) { 2077 executeOpsTogether(records, isRecordPop, startIndex, recordNum); 2078 } 2079 // execute all unoptimized together 2080 int optimizeEnd; 2081 for (optimizeEnd = recordNum + 1; optimizeEnd < numRecords; optimizeEnd++) { 2082 if (records.get(optimizeEnd).mAllowOptimization) { 2083 break; 2084 } 2085 } 2086 executeOpsTogether(records, isRecordPop, recordNum, optimizeEnd); 2087 startIndex = optimizeEnd; 2088 recordNum = optimizeEnd - 1; 2089 } 2090 } 2091 if (startIndex != numRecords) { 2092 executeOpsTogether(records, isRecordPop, startIndex, numRecords); 2093 } 2094 } 2095 2096 /** 2097 * Optimizes a subset of a list of BackStackRecords, all of which either allow optimization or 2098 * do not allow optimization. 2099 * @param records A list of BackStackRecords that are to be optimized 2100 * @param isRecordPop The direction that these records are being run. 2101 * @param startIndex The index of the first record in <code>records</code> to be optimized 2102 * @param endIndex One more than the final record index in <code>records</code> to optimize. 2103 */ 2104 private void executeOpsTogether(ArrayList<BackStackRecord> records, 2105 ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { 2106 final boolean allowOptimization = records.get(startIndex).mAllowOptimization; 2107 boolean addToBackStack = false; 2108 if (mTmpAddedFragments == null) { 2109 mTmpAddedFragments = new ArrayList<>(); 2110 } else { 2111 mTmpAddedFragments.clear(); 2112 } 2113 if (mAdded != null) { 2114 mTmpAddedFragments.addAll(mAdded); 2115 } 2116 for (int recordNum = startIndex; recordNum < endIndex; recordNum++) { 2117 final BackStackRecord record = records.get(recordNum); 2118 final boolean isPop = isRecordPop.get(recordNum); 2119 if (!isPop) { 2120 record.expandReplaceOps(mTmpAddedFragments); 2121 } 2122 final int bumpAmount = isPop ? -1 : 1; 2123 record.bumpBackStackNesting(bumpAmount); 2124 addToBackStack = addToBackStack || record.mAddToBackStack; 2125 } 2126 mTmpAddedFragments.clear(); 2127 2128 if (!allowOptimization) { 2129 FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, endIndex, 2130 false); 2131 } 2132 executeOps(records, isRecordPop, startIndex, endIndex); 2133 2134 int postponeIndex = endIndex; 2135 if (allowOptimization) { 2136 moveFragmentsToInvisible(); 2137 postponeIndex = postponePostponableTransactions(records, isRecordPop, 2138 startIndex, endIndex); 2139 } 2140 2141 if (postponeIndex != startIndex && allowOptimization) { 2142 // need to run something now 2143 FragmentTransition.startTransitions(this, records, isRecordPop, startIndex, 2144 postponeIndex, true); 2145 moveToState(mCurState, true); 2146 } 2147 2148 for (int recordNum = startIndex; recordNum < endIndex; recordNum++) { 2149 final BackStackRecord record = records.get(recordNum); 2150 final boolean isPop = isRecordPop.get(recordNum); 2151 if (isPop && record.mIndex >= 0) { 2152 freeBackStackIndex(record.mIndex); 2153 record.mIndex = -1; 2154 } 2155 } 2156 if (addToBackStack) { 2157 reportBackStackChanged(); 2158 } 2159 } 2160 2161 /** 2162 * Examine all transactions and determine which ones are marked as postponed. Those will 2163 * have their operations rolled back and moved to the end of the record list (up to endIndex). 2164 * It will also add the postponed transaction to the queue. 2165 * 2166 * @param records A list of BackStackRecords that should be checked. 2167 * @param isRecordPop The direction that these records are being run. 2168 * @param startIndex The index of the first record in <code>records</code> to be checked 2169 * @param endIndex One more than the final record index in <code>records</code> to be checked. 2170 * @return The index of the first postponed transaction or endIndex if no transaction was 2171 * postponed. 2172 */ 2173 private int postponePostponableTransactions(ArrayList<BackStackRecord> records, 2174 ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { 2175 int postponeIndex = endIndex; 2176 for (int i = endIndex - 1; i >= startIndex; i--) { 2177 final BackStackRecord record = records.get(i); 2178 final boolean isPop = isRecordPop.get(i); 2179 boolean isPostponed = record.isPostponed() 2180 && !record.interactsWith(records, i + 1, endIndex); 2181 if (isPostponed) { 2182 if (mPostponedTransactions == null) { 2183 mPostponedTransactions = new ArrayList<>(); 2184 } 2185 StartEnterTransitionListener listener = 2186 new StartEnterTransitionListener(record, isPop); 2187 mPostponedTransactions.add(listener); 2188 record.setOnStartPostponedListener(listener); 2189 2190 // roll back the transaction 2191 if (isPop) { 2192 record.executeOps(); 2193 } else { 2194 record.executePopOps(); 2195 } 2196 2197 // move to the end 2198 postponeIndex--; 2199 if (i != postponeIndex) { 2200 records.remove(i); 2201 records.add(postponeIndex, record); 2202 } 2203 2204 // different views may be visible now 2205 moveFragmentsToInvisible(); 2206 } 2207 } 2208 return postponeIndex; 2209 } 2210 2211 /** 2212 * When a postponed transaction is ready to be started, this completes the transaction, 2213 * removing, hiding, or showing views as well as starting the animations and transitions. 2214 * <p> 2215 * {@code runtransitions} is set to false when the transaction postponement was interrupted 2216 * abnormally -- normally by a new transaction being started that affects the postponed 2217 * transaction. 2218 * 2219 * @param record The transaction to run 2220 * @param isPop true if record is popping or false if it is adding 2221 * @param runTransitions true if the fragment transition should be run or false otherwise. 2222 * @param moveToState true if the state should be changed after executing the operations. 2223 * This is false when the transaction is canceled when a postponed 2224 * transaction is popped. 2225 */ 2226 private void completeExecute(BackStackRecord record, boolean isPop, boolean runTransitions, 2227 boolean moveToState) { 2228 ArrayList<BackStackRecord> records = new ArrayList<>(1); 2229 ArrayList<Boolean> isRecordPop = new ArrayList<>(1); 2230 records.add(record); 2231 isRecordPop.add(isPop); 2232 executeOps(records, isRecordPop, 0, 1); 2233 if (runTransitions) { 2234 FragmentTransition.startTransitions(this, records, isRecordPop, 0, 1, true); 2235 } 2236 if (moveToState) { 2237 moveToState(mCurState, true); 2238 } else if (mActive != null) { 2239 final int numActive = mActive.size(); 2240 for (int i = 0; i < numActive; i++) { 2241 // Allow added fragments to be removed during the pop since we aren't going 2242 // to move them to the final state with moveToState(mCurState). 2243 Fragment fragment = mActive.get(i); 2244 if (fragment.mView != null && fragment.mIsNewlyAdded 2245 && record.interactsWith(fragment.mContainerId)) { 2246 fragment.mIsNewlyAdded = false; 2247 } 2248 } 2249 } 2250 } 2251 2252 /** 2253 * Find a fragment within the fragment's container whose View should be below the passed 2254 * fragment. {@code null} is returned when the fragment has no View or if there should be 2255 * no fragment with a View below the given fragment. 2256 * 2257 * As an example, if mAdded has two Fragments with Views sharing the same container: 2258 * FragmentA 2259 * FragmentB 2260 * 2261 * Then, when processing FragmentB, FragmentA will be returned. If, however, FragmentA 2262 * had no View, null would be returned. 2263 * 2264 * @param f The fragment that may be on top of another fragment. 2265 * @return The fragment with a View under f, if one exists or null if f has no View or 2266 * there are no fragments with Views in the same container. 2267 */ 2268 private Fragment findFragmentUnder(Fragment f) { 2269 final ViewGroup container = f.mContainer; 2270 final View view = f.mView; 2271 2272 if (container == null || view == null) { 2273 return null; 2274 } 2275 2276 final int fragmentIndex = mAdded.indexOf(f); 2277 for (int i = fragmentIndex - 1; i >= 0; i--) { 2278 Fragment underFragment = mAdded.get(i); 2279 if (underFragment.mContainer == container && underFragment.mView != null) { 2280 // Found the fragment under this one 2281 return underFragment; 2282 } 2283 } 2284 return null; 2285 } 2286 2287 /** 2288 * Run the operations in the BackStackRecords, either to push or pop. 2289 * 2290 * @param records The list of records whose operations should be run. 2291 * @param isRecordPop The direction that these records are being run. 2292 * @param startIndex The index of the first entry in records to run. 2293 * @param endIndex One past the index of the final entry in records to run. 2294 */ 2295 private static void executeOps(ArrayList<BackStackRecord> records, 2296 ArrayList<Boolean> isRecordPop, int startIndex, int endIndex) { 2297 for (int i = startIndex; i < endIndex; i++) { 2298 final BackStackRecord record = records.get(i); 2299 final boolean isPop = isRecordPop.get(i); 2300 if (isPop) { 2301 record.executePopOps(); 2302 } else { 2303 record.executeOps(); 2304 } 2305 } 2306 } 2307 2308 /** 2309 * Ensure that fragments that are added are moved to at least the CREATED state. 2310 * Any newly-added Views are made INVISIBLE so that the Transaction can be postponed 2311 * with {@link Fragment#postponeEnterTransition()}. 2312 */ 2313 private void moveFragmentsToInvisible() { 2314 if (mCurState < Fragment.CREATED) { 2315 return; 2316 } 2317 // We want to leave the fragment in the started state 2318 final int state = Math.min(mCurState, Fragment.STARTED); 2319 final int numAdded = mAdded == null ? 0 : mAdded.size(); 2320 for (int i = 0; i < numAdded; i++) { 2321 Fragment fragment = mAdded.get(i); 2322 if (fragment.mState < state) { 2323 moveToState(fragment, state, fragment.getNextAnim(), fragment.getNextTransition(), 2324 false); 2325 if (fragment.mView != null && !fragment.mHidden && fragment.mIsNewlyAdded) { 2326 fragment.mView.setVisibility(View.INVISIBLE); 2327 } 2328 } 2329 } 2330 } 2331 2332 /** 2333 * Starts all postponed transactions regardless of whether they are ready or not. 2334 */ 2335 private void forcePostponedTransactions() { 2336 if (mPostponedTransactions != null) { 2337 while (!mPostponedTransactions.isEmpty()) { 2338 mPostponedTransactions.remove(0).completeTransaction(); 2339 } 2340 } 2341 } 2342 2343 /** 2344 * Ends the animations of fragments so that they immediately reach the end state. 2345 * This is used prior to saving the state so that the correct state is saved. 2346 */ 2347 private void endAnimatingAwayFragments() { 2348 final int numFragments = mActive == null ? 0 : mActive.size(); 2349 for (int i = 0; i < numFragments; i++) { 2350 Fragment fragment = mActive.get(i); 2351 if (fragment != null && fragment.getAnimatingAway() != null) { 2352 // Give up waiting for the animation and just end it. 2353 final int stateAfterAnimating = fragment.getStateAfterAnimating(); 2354 final View animatingAway = fragment.getAnimatingAway(); 2355 fragment.setAnimatingAway(null); 2356 animatingAway.clearAnimation(); 2357 moveToState(fragment, stateAfterAnimating, 0, 0, false); 2358 } 2359 } 2360 } 2361 2362 /** 2363 * Adds all records in the pending actions to records and whether they are add or pop 2364 * operations to isPop. After executing, the pending actions will be empty. 2365 * 2366 * @param records All pending actions will generate BackStackRecords added to this. 2367 * This contains the transactions, in order, to execute. 2368 * @param isPop All pending actions will generate booleans to add to this. This contains 2369 * an entry for each entry in records to indicate whether or not it is a 2370 * pop action. 2371 */ 2372 private boolean generateOpsForPendingActions(ArrayList<BackStackRecord> records, 2373 ArrayList<Boolean> isPop) { 2374 int numActions; 2375 synchronized (this) { 2376 if (mPendingActions == null || mPendingActions.size() == 0) { 2377 return false; 2378 } 2379 2380 numActions = mPendingActions.size(); 2381 for (int i = 0; i < numActions; i++) { 2382 mPendingActions.get(i).generateOps(records, isPop); 2383 } 2384 mPendingActions.clear(); 2385 mHost.getHandler().removeCallbacks(mExecCommit); 2386 } 2387 return numActions > 0; 2388 } 2389 2390 void doPendingDeferredStart() { 2391 if (mHavePendingDeferredStart) { 2392 boolean loadersRunning = false; 2393 for (int i = 0; i < mActive.size(); i++) { 2394 Fragment f = mActive.get(i); 2395 if (f != null && f.mLoaderManager != null) { 2396 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 2397 } 2398 } 2399 if (!loadersRunning) { 2400 mHavePendingDeferredStart = false; 2401 startPendingDeferredFragments(); 2402 } 2403 } 2404 } 2405 2406 void reportBackStackChanged() { 2407 if (mBackStackChangeListeners != null) { 2408 for (int i=0; i<mBackStackChangeListeners.size(); i++) { 2409 mBackStackChangeListeners.get(i).onBackStackChanged(); 2410 } 2411 } 2412 } 2413 2414 void addBackStackState(BackStackRecord state) { 2415 if (mBackStack == null) { 2416 mBackStack = new ArrayList<BackStackRecord>(); 2417 } 2418 mBackStack.add(state); 2419 reportBackStackChanged(); 2420 } 2421 2422 @SuppressWarnings("unused") 2423 boolean popBackStackState(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop, 2424 String name, int id, int flags) { 2425 if (mBackStack == null) { 2426 return false; 2427 } 2428 if (name == null && id < 0 && (flags & POP_BACK_STACK_INCLUSIVE) == 0) { 2429 int last = mBackStack.size() - 1; 2430 if (last < 0) { 2431 return false; 2432 } 2433 records.add(mBackStack.remove(last)); 2434 isRecordPop.add(true); 2435 } else { 2436 int index = -1; 2437 if (name != null || id >= 0) { 2438 // If a name or ID is specified, look for that place in 2439 // the stack. 2440 index = mBackStack.size()-1; 2441 while (index >= 0) { 2442 BackStackRecord bss = mBackStack.get(index); 2443 if (name != null && name.equals(bss.getName())) { 2444 break; 2445 } 2446 if (id >= 0 && id == bss.mIndex) { 2447 break; 2448 } 2449 index--; 2450 } 2451 if (index < 0) { 2452 return false; 2453 } 2454 if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) { 2455 index--; 2456 // Consume all following entries that match. 2457 while (index >= 0) { 2458 BackStackRecord bss = mBackStack.get(index); 2459 if ((name != null && name.equals(bss.getName())) 2460 || (id >= 0 && id == bss.mIndex)) { 2461 index--; 2462 continue; 2463 } 2464 break; 2465 } 2466 } 2467 } 2468 if (index == mBackStack.size()-1) { 2469 return false; 2470 } 2471 for (int i = mBackStack.size() - 1; i > index; i--) { 2472 records.add(mBackStack.remove(i)); 2473 isRecordPop.add(true); 2474 } 2475 } 2476 return true; 2477 } 2478 2479 FragmentManagerNonConfig retainNonConfig() { 2480 ArrayList<Fragment> fragments = null; 2481 ArrayList<FragmentManagerNonConfig> childFragments = null; 2482 if (mActive != null) { 2483 for (int i=0; i<mActive.size(); i++) { 2484 Fragment f = mActive.get(i); 2485 if (f != null) { 2486 if (f.mRetainInstance) { 2487 if (fragments == null) { 2488 fragments = new ArrayList<Fragment>(); 2489 } 2490 fragments.add(f); 2491 f.mRetaining = true; 2492 f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1; 2493 if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f); 2494 } 2495 boolean addedChild = false; 2496 if (f.mChildFragmentManager != null) { 2497 FragmentManagerNonConfig child = f.mChildFragmentManager.retainNonConfig(); 2498 if (child != null) { 2499 if (childFragments == null) { 2500 childFragments = new ArrayList<FragmentManagerNonConfig>(); 2501 for (int j = 0; j < i; j++) { 2502 childFragments.add(null); 2503 } 2504 } 2505 childFragments.add(child); 2506 addedChild = true; 2507 } 2508 } 2509 if (childFragments != null && !addedChild) { 2510 childFragments.add(null); 2511 } 2512 } 2513 } 2514 } 2515 if (fragments == null && childFragments == null) { 2516 return null; 2517 } 2518 return new FragmentManagerNonConfig(fragments, childFragments); 2519 } 2520 2521 void saveFragmentViewState(Fragment f) { 2522 if (f.mInnerView == null) { 2523 return; 2524 } 2525 if (mStateArray == null) { 2526 mStateArray = new SparseArray<Parcelable>(); 2527 } else { 2528 mStateArray.clear(); 2529 } 2530 f.mInnerView.saveHierarchyState(mStateArray); 2531 if (mStateArray.size() > 0) { 2532 f.mSavedViewState = mStateArray; 2533 mStateArray = null; 2534 } 2535 } 2536 2537 Bundle saveFragmentBasicState(Fragment f) { 2538 Bundle result = null; 2539 2540 if (mStateBundle == null) { 2541 mStateBundle = new Bundle(); 2542 } 2543 f.performSaveInstanceState(mStateBundle); 2544 dispatchOnFragmentSaveInstanceState(f, mStateBundle, false); 2545 if (!mStateBundle.isEmpty()) { 2546 result = mStateBundle; 2547 mStateBundle = null; 2548 } 2549 2550 if (f.mView != null) { 2551 saveFragmentViewState(f); 2552 } 2553 if (f.mSavedViewState != null) { 2554 if (result == null) { 2555 result = new Bundle(); 2556 } 2557 result.putSparseParcelableArray( 2558 FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState); 2559 } 2560 if (!f.mUserVisibleHint) { 2561 if (result == null) { 2562 result = new Bundle(); 2563 } 2564 // Only add this if it's not the default value 2565 result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint); 2566 } 2567 2568 return result; 2569 } 2570 2571 Parcelable saveAllState() { 2572 // Make sure all pending operations have now been executed to get 2573 // our state update-to-date. 2574 forcePostponedTransactions(); 2575 endAnimatingAwayFragments(); 2576 execPendingActions(); 2577 2578 if (HONEYCOMB) { 2579 // As of Honeycomb, we save state after pausing. Prior to that 2580 // it is before pausing. With fragments this is an issue, since 2581 // there are many things you may do after pausing but before 2582 // stopping that change the fragment state. For those older 2583 // devices, we will not at this point say that we have saved 2584 // the state, so we will allow them to continue doing fragment 2585 // transactions. This retains the same semantics as Honeycomb, 2586 // though you do have the risk of losing the very most recent state 2587 // if the process is killed... we'll live with that. 2588 mStateSaved = true; 2589 } 2590 2591 if (mActive == null || mActive.size() <= 0) { 2592 return null; 2593 } 2594 2595 // First collect all active fragments. 2596 int N = mActive.size(); 2597 FragmentState[] active = new FragmentState[N]; 2598 boolean haveFragments = false; 2599 for (int i=0; i<N; i++) { 2600 Fragment f = mActive.get(i); 2601 if (f != null) { 2602 if (f.mIndex < 0) { 2603 throwException(new IllegalStateException( 2604 "Failure saving state: active " + f 2605 + " has cleared index: " + f.mIndex)); 2606 } 2607 2608 haveFragments = true; 2609 2610 FragmentState fs = new FragmentState(f); 2611 active[i] = fs; 2612 2613 if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) { 2614 fs.mSavedFragmentState = saveFragmentBasicState(f); 2615 2616 if (f.mTarget != null) { 2617 if (f.mTarget.mIndex < 0) { 2618 throwException(new IllegalStateException( 2619 "Failure saving state: " + f 2620 + " has target not in fragment manager: " + f.mTarget)); 2621 } 2622 if (fs.mSavedFragmentState == null) { 2623 fs.mSavedFragmentState = new Bundle(); 2624 } 2625 putFragment(fs.mSavedFragmentState, 2626 FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget); 2627 if (f.mTargetRequestCode != 0) { 2628 fs.mSavedFragmentState.putInt( 2629 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 2630 f.mTargetRequestCode); 2631 } 2632 } 2633 2634 } else { 2635 fs.mSavedFragmentState = f.mSavedFragmentState; 2636 } 2637 2638 if (DEBUG) Log.v(TAG, "Saved state of " + f + ": " 2639 + fs.mSavedFragmentState); 2640 } 2641 } 2642 2643 if (!haveFragments) { 2644 if (DEBUG) Log.v(TAG, "saveAllState: no fragments!"); 2645 return null; 2646 } 2647 2648 int[] added = null; 2649 BackStackState[] backStack = null; 2650 2651 // Build list of currently added fragments. 2652 if (mAdded != null) { 2653 N = mAdded.size(); 2654 if (N > 0) { 2655 added = new int[N]; 2656 for (int i=0; i<N; i++) { 2657 added[i] = mAdded.get(i).mIndex; 2658 if (added[i] < 0) { 2659 throwException(new IllegalStateException( 2660 "Failure saving state: active " + mAdded.get(i) 2661 + " has cleared index: " + added[i])); 2662 } 2663 if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i 2664 + ": " + mAdded.get(i)); 2665 } 2666 } 2667 } 2668 2669 // Now save back stack. 2670 if (mBackStack != null) { 2671 N = mBackStack.size(); 2672 if (N > 0) { 2673 backStack = new BackStackState[N]; 2674 for (int i=0; i<N; i++) { 2675 backStack[i] = new BackStackState(mBackStack.get(i)); 2676 if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i 2677 + ": " + mBackStack.get(i)); 2678 } 2679 } 2680 } 2681 2682 FragmentManagerState fms = new FragmentManagerState(); 2683 fms.mActive = active; 2684 fms.mAdded = added; 2685 fms.mBackStack = backStack; 2686 return fms; 2687 } 2688 2689 void restoreAllState(Parcelable state, FragmentManagerNonConfig nonConfig) { 2690 // If there is no saved state at all, then there can not be 2691 // any nonConfig fragments either, so that is that. 2692 if (state == null) return; 2693 FragmentManagerState fms = (FragmentManagerState)state; 2694 if (fms.mActive == null) return; 2695 2696 List<FragmentManagerNonConfig> childNonConfigs = null; 2697 2698 // First re-attach any non-config instances we are retaining back 2699 // to their saved state, so we don't try to instantiate them again. 2700 if (nonConfig != null) { 2701 List<Fragment> nonConfigFragments = nonConfig.getFragments(); 2702 childNonConfigs = nonConfig.getChildNonConfigs(); 2703 final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0; 2704 for (int i = 0; i < count; i++) { 2705 Fragment f = nonConfigFragments.get(i); 2706 if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f); 2707 FragmentState fs = fms.mActive[f.mIndex]; 2708 fs.mInstance = f; 2709 f.mSavedViewState = null; 2710 f.mBackStackNesting = 0; 2711 f.mInLayout = false; 2712 f.mAdded = false; 2713 f.mTarget = null; 2714 if (fs.mSavedFragmentState != null) { 2715 fs.mSavedFragmentState.setClassLoader(mHost.getContext().getClassLoader()); 2716 f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray( 2717 FragmentManagerImpl.VIEW_STATE_TAG); 2718 f.mSavedFragmentState = fs.mSavedFragmentState; 2719 } 2720 } 2721 } 2722 2723 // Build the full list of active fragments, instantiating them from 2724 // their saved state. 2725 mActive = new ArrayList<>(fms.mActive.length); 2726 if (mAvailIndices != null) { 2727 mAvailIndices.clear(); 2728 } 2729 for (int i=0; i<fms.mActive.length; i++) { 2730 FragmentState fs = fms.mActive[i]; 2731 if (fs != null) { 2732 FragmentManagerNonConfig childNonConfig = null; 2733 if (childNonConfigs != null && i < childNonConfigs.size()) { 2734 childNonConfig = childNonConfigs.get(i); 2735 } 2736 Fragment f = fs.instantiate(mHost, mParent, childNonConfig); 2737 if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f); 2738 mActive.add(f); 2739 // Now that the fragment is instantiated (or came from being 2740 // retained above), clear mInstance in case we end up re-restoring 2741 // from this FragmentState again. 2742 fs.mInstance = null; 2743 } else { 2744 mActive.add(null); 2745 if (mAvailIndices == null) { 2746 mAvailIndices = new ArrayList<Integer>(); 2747 } 2748 if (DEBUG) Log.v(TAG, "restoreAllState: avail #" + i); 2749 mAvailIndices.add(i); 2750 } 2751 } 2752 2753 // Update the target of all retained fragments. 2754 if (nonConfig != null) { 2755 List<Fragment> nonConfigFragments = nonConfig.getFragments(); 2756 final int count = nonConfigFragments != null ? nonConfigFragments.size() : 0; 2757 for (int i = 0; i < count; i++) { 2758 Fragment f = nonConfigFragments.get(i); 2759 if (f.mTargetIndex >= 0) { 2760 if (f.mTargetIndex < mActive.size()) { 2761 f.mTarget = mActive.get(f.mTargetIndex); 2762 } else { 2763 Log.w(TAG, "Re-attaching retained fragment " + f 2764 + " target no longer exists: " + f.mTargetIndex); 2765 f.mTarget = null; 2766 } 2767 } 2768 } 2769 } 2770 2771 // Build the list of currently added fragments. 2772 if (fms.mAdded != null) { 2773 mAdded = new ArrayList<Fragment>(fms.mAdded.length); 2774 for (int i=0; i<fms.mAdded.length; i++) { 2775 Fragment f = mActive.get(fms.mAdded[i]); 2776 if (f == null) { 2777 throwException(new IllegalStateException( 2778 "No instantiated fragment for index #" + fms.mAdded[i])); 2779 } 2780 f.mAdded = true; 2781 if (DEBUG) Log.v(TAG, "restoreAllState: added #" + i + ": " + f); 2782 if (mAdded.contains(f)) { 2783 throw new IllegalStateException("Already added!"); 2784 } 2785 mAdded.add(f); 2786 } 2787 } else { 2788 mAdded = null; 2789 } 2790 2791 // Build the back stack. 2792 if (fms.mBackStack != null) { 2793 mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length); 2794 for (int i=0; i<fms.mBackStack.length; i++) { 2795 BackStackRecord bse = fms.mBackStack[i].instantiate(this); 2796 if (DEBUG) { 2797 Log.v(TAG, "restoreAllState: back stack #" + i 2798 + " (index " + bse.mIndex + "): " + bse); 2799 LogWriter logw = new LogWriter(TAG); 2800 PrintWriter pw = new PrintWriter(logw); 2801 bse.dump(" ", pw, false); 2802 } 2803 mBackStack.add(bse); 2804 if (bse.mIndex >= 0) { 2805 setBackStackIndex(bse.mIndex, bse); 2806 } 2807 } 2808 } else { 2809 mBackStack = null; 2810 } 2811 } 2812 2813 public void attachController(FragmentHostCallback host, 2814 FragmentContainer container, Fragment parent) { 2815 if (mHost != null) throw new IllegalStateException("Already attached"); 2816 mHost = host; 2817 mContainer = container; 2818 mParent = parent; 2819 } 2820 2821 public void noteStateNotSaved() { 2822 mStateSaved = false; 2823 } 2824 2825 public void dispatchCreate() { 2826 mStateSaved = false; 2827 moveToState(Fragment.CREATED, false); 2828 } 2829 2830 public void dispatchActivityCreated() { 2831 mStateSaved = false; 2832 moveToState(Fragment.ACTIVITY_CREATED, false); 2833 } 2834 2835 public void dispatchStart() { 2836 mStateSaved = false; 2837 moveToState(Fragment.STARTED, false); 2838 } 2839 2840 public void dispatchResume() { 2841 mStateSaved = false; 2842 moveToState(Fragment.RESUMED, false); 2843 } 2844 2845 public void dispatchPause() { 2846 moveToState(Fragment.STARTED, false); 2847 } 2848 2849 public void dispatchStop() { 2850 // See saveAllState() for the explanation of this. We do this for 2851 // all platform versions, to keep our behavior more consistent between 2852 // them. 2853 mStateSaved = true; 2854 2855 moveToState(Fragment.STOPPED, false); 2856 } 2857 2858 public void dispatchReallyStop() { 2859 moveToState(Fragment.ACTIVITY_CREATED, false); 2860 } 2861 2862 public void dispatchDestroyView() { 2863 moveToState(Fragment.CREATED, false); 2864 } 2865 2866 public void dispatchDestroy() { 2867 mDestroyed = true; 2868 execPendingActions(); 2869 moveToState(Fragment.INITIALIZING, false); 2870 mHost = null; 2871 mContainer = null; 2872 mParent = null; 2873 } 2874 2875 public void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode) { 2876 if (mAdded == null) { 2877 return; 2878 } 2879 for (int i = mAdded.size() - 1; i >= 0; --i) { 2880 final android.support.v4.app.Fragment f = mAdded.get(i); 2881 if (f != null) { 2882 f.performMultiWindowModeChanged(isInMultiWindowMode); 2883 } 2884 } 2885 } 2886 2887 public void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode) { 2888 if (mAdded == null) { 2889 return; 2890 } 2891 for (int i = mAdded.size() - 1; i >= 0; --i) { 2892 final android.support.v4.app.Fragment f = mAdded.get(i); 2893 if (f != null) { 2894 f.performPictureInPictureModeChanged(isInPictureInPictureMode); 2895 } 2896 } 2897 } 2898 2899 public void dispatchConfigurationChanged(Configuration newConfig) { 2900 if (mAdded != null) { 2901 for (int i=0; i<mAdded.size(); i++) { 2902 Fragment f = mAdded.get(i); 2903 if (f != null) { 2904 f.performConfigurationChanged(newConfig); 2905 } 2906 } 2907 } 2908 } 2909 2910 public void dispatchLowMemory() { 2911 if (mAdded != null) { 2912 for (int i=0; i<mAdded.size(); i++) { 2913 Fragment f = mAdded.get(i); 2914 if (f != null) { 2915 f.performLowMemory(); 2916 } 2917 } 2918 } 2919 } 2920 2921 public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) { 2922 boolean show = false; 2923 ArrayList<Fragment> newMenus = null; 2924 if (mAdded != null) { 2925 for (int i=0; i<mAdded.size(); i++) { 2926 Fragment f = mAdded.get(i); 2927 if (f != null) { 2928 if (f.performCreateOptionsMenu(menu, inflater)) { 2929 show = true; 2930 if (newMenus == null) { 2931 newMenus = new ArrayList<Fragment>(); 2932 } 2933 newMenus.add(f); 2934 } 2935 } 2936 } 2937 } 2938 2939 if (mCreatedMenus != null) { 2940 for (int i=0; i<mCreatedMenus.size(); i++) { 2941 Fragment f = mCreatedMenus.get(i); 2942 if (newMenus == null || !newMenus.contains(f)) { 2943 f.onDestroyOptionsMenu(); 2944 } 2945 } 2946 } 2947 2948 mCreatedMenus = newMenus; 2949 2950 return show; 2951 } 2952 2953 public boolean dispatchPrepareOptionsMenu(Menu menu) { 2954 boolean show = false; 2955 if (mAdded != null) { 2956 for (int i=0; i<mAdded.size(); i++) { 2957 Fragment f = mAdded.get(i); 2958 if (f != null) { 2959 if (f.performPrepareOptionsMenu(menu)) { 2960 show = true; 2961 } 2962 } 2963 } 2964 } 2965 return show; 2966 } 2967 2968 public boolean dispatchOptionsItemSelected(MenuItem item) { 2969 if (mAdded != null) { 2970 for (int i=0; i<mAdded.size(); i++) { 2971 Fragment f = mAdded.get(i); 2972 if (f != null) { 2973 if (f.performOptionsItemSelected(item)) { 2974 return true; 2975 } 2976 } 2977 } 2978 } 2979 return false; 2980 } 2981 2982 public boolean dispatchContextItemSelected(MenuItem item) { 2983 if (mAdded != null) { 2984 for (int i=0; i<mAdded.size(); i++) { 2985 Fragment f = mAdded.get(i); 2986 if (f != null) { 2987 if (f.performContextItemSelected(item)) { 2988 return true; 2989 } 2990 } 2991 } 2992 } 2993 return false; 2994 } 2995 2996 public void dispatchOptionsMenuClosed(Menu menu) { 2997 if (mAdded != null) { 2998 for (int i=0; i<mAdded.size(); i++) { 2999 Fragment f = mAdded.get(i); 3000 if (f != null) { 3001 f.performOptionsMenuClosed(menu); 3002 } 3003 } 3004 } 3005 } 3006 3007 public void registerFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb, 3008 boolean recursive) { 3009 if (mLifecycleCallbacks == null) { 3010 mLifecycleCallbacks = new CopyOnWriteArrayList<>(); 3011 } 3012 mLifecycleCallbacks.add(new Pair(cb, recursive)); 3013 } 3014 3015 public void unregisterFragmentLifecycleCallbacks(FragmentLifecycleCallbacks cb) { 3016 if (mLifecycleCallbacks == null) { 3017 return; 3018 } 3019 3020 synchronized (mLifecycleCallbacks) { 3021 for (int i = 0, N = mLifecycleCallbacks.size(); i < N; i++) { 3022 if (mLifecycleCallbacks.get(i).first == cb) { 3023 mLifecycleCallbacks.remove(i); 3024 break; 3025 } 3026 } 3027 } 3028 } 3029 3030 void dispatchOnFragmentPreAttached(Fragment f, Context context, boolean onlyRecursive) { 3031 if (mParent != null) { 3032 FragmentManager parentManager = mParent.getFragmentManager(); 3033 if (parentManager instanceof FragmentManagerImpl) { 3034 ((FragmentManagerImpl) parentManager) 3035 .dispatchOnFragmentPreAttached(f, context, true); 3036 } 3037 } 3038 if (mLifecycleCallbacks == null) { 3039 return; 3040 } 3041 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3042 if (!onlyRecursive || p.second) { 3043 p.first.onFragmentPreAttached(this, f, context); 3044 } 3045 } 3046 } 3047 3048 void dispatchOnFragmentAttached(Fragment f, Context context, boolean onlyRecursive) { 3049 if (mParent != null) { 3050 FragmentManager parentManager = mParent.getFragmentManager(); 3051 if (parentManager instanceof FragmentManagerImpl) { 3052 ((FragmentManagerImpl) parentManager) 3053 .dispatchOnFragmentAttached(f, context, true); 3054 } 3055 } 3056 if (mLifecycleCallbacks == null) { 3057 return; 3058 } 3059 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3060 if (!onlyRecursive || p.second) { 3061 p.first.onFragmentAttached(this, f, context); 3062 } 3063 } 3064 } 3065 3066 void dispatchOnFragmentCreated(Fragment f, Bundle savedInstanceState, boolean onlyRecursive) { 3067 if (mParent != null) { 3068 FragmentManager parentManager = mParent.getFragmentManager(); 3069 if (parentManager instanceof FragmentManagerImpl) { 3070 ((FragmentManagerImpl) parentManager) 3071 .dispatchOnFragmentCreated(f, savedInstanceState, true); 3072 } 3073 } 3074 if (mLifecycleCallbacks == null) { 3075 return; 3076 } 3077 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3078 if (!onlyRecursive || p.second) { 3079 p.first.onFragmentCreated(this, f, savedInstanceState); 3080 } 3081 } 3082 } 3083 3084 void dispatchOnFragmentActivityCreated(Fragment f, Bundle savedInstanceState, 3085 boolean onlyRecursive) { 3086 if (mParent != null) { 3087 FragmentManager parentManager = mParent.getFragmentManager(); 3088 if (parentManager instanceof FragmentManagerImpl) { 3089 ((FragmentManagerImpl) parentManager) 3090 .dispatchOnFragmentActivityCreated(f, savedInstanceState, true); 3091 } 3092 } 3093 if (mLifecycleCallbacks == null) { 3094 return; 3095 } 3096 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3097 if (!onlyRecursive || p.second) { 3098 p.first.onFragmentActivityCreated(this, f, savedInstanceState); 3099 } 3100 } 3101 } 3102 3103 void dispatchOnFragmentViewCreated(Fragment f, View v, Bundle savedInstanceState, 3104 boolean onlyRecursive) { 3105 if (mParent != null) { 3106 FragmentManager parentManager = mParent.getFragmentManager(); 3107 if (parentManager instanceof FragmentManagerImpl) { 3108 ((FragmentManagerImpl) parentManager) 3109 .dispatchOnFragmentViewCreated(f, v, savedInstanceState, true); 3110 } 3111 } 3112 if (mLifecycleCallbacks == null) { 3113 return; 3114 } 3115 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3116 if (!onlyRecursive || p.second) { 3117 p.first.onFragmentViewCreated(this, f, v, savedInstanceState); 3118 } 3119 } 3120 } 3121 3122 void dispatchOnFragmentStarted(Fragment f, boolean onlyRecursive) { 3123 if (mParent != null) { 3124 FragmentManager parentManager = mParent.getFragmentManager(); 3125 if (parentManager instanceof FragmentManagerImpl) { 3126 ((FragmentManagerImpl) parentManager) 3127 .dispatchOnFragmentStarted(f, true); 3128 } 3129 } 3130 if (mLifecycleCallbacks == null) { 3131 return; 3132 } 3133 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3134 if (!onlyRecursive || p.second) { 3135 p.first.onFragmentStarted(this, f); 3136 } 3137 } 3138 } 3139 3140 void dispatchOnFragmentResumed(Fragment f, boolean onlyRecursive) { 3141 if (mParent != null) { 3142 FragmentManager parentManager = mParent.getFragmentManager(); 3143 if (parentManager instanceof FragmentManagerImpl) { 3144 ((FragmentManagerImpl) parentManager) 3145 .dispatchOnFragmentResumed(f, true); 3146 } 3147 } 3148 if (mLifecycleCallbacks == null) { 3149 return; 3150 } 3151 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3152 if (!onlyRecursive || p.second) { 3153 p.first.onFragmentResumed(this, f); 3154 } 3155 } 3156 } 3157 3158 void dispatchOnFragmentPaused(Fragment f, boolean onlyRecursive) { 3159 if (mParent != null) { 3160 FragmentManager parentManager = mParent.getFragmentManager(); 3161 if (parentManager instanceof FragmentManagerImpl) { 3162 ((FragmentManagerImpl) parentManager) 3163 .dispatchOnFragmentPaused(f, true); 3164 } 3165 } 3166 if (mLifecycleCallbacks == null) { 3167 return; 3168 } 3169 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3170 if (!onlyRecursive || p.second) { 3171 p.first.onFragmentPaused(this, f); 3172 } 3173 } 3174 } 3175 3176 void dispatchOnFragmentStopped(Fragment f, boolean onlyRecursive) { 3177 if (mParent != null) { 3178 FragmentManager parentManager = mParent.getFragmentManager(); 3179 if (parentManager instanceof FragmentManagerImpl) { 3180 ((FragmentManagerImpl) parentManager) 3181 .dispatchOnFragmentStopped(f, true); 3182 } 3183 } 3184 if (mLifecycleCallbacks == null) { 3185 return; 3186 } 3187 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3188 if (!onlyRecursive || p.second) { 3189 p.first.onFragmentStopped(this, f); 3190 } 3191 } 3192 } 3193 3194 void dispatchOnFragmentSaveInstanceState(Fragment f, Bundle outState, boolean onlyRecursive) { 3195 if (mParent != null) { 3196 FragmentManager parentManager = mParent.getFragmentManager(); 3197 if (parentManager instanceof FragmentManagerImpl) { 3198 ((FragmentManagerImpl) parentManager) 3199 .dispatchOnFragmentSaveInstanceState(f, outState, true); 3200 } 3201 } 3202 if (mLifecycleCallbacks == null) { 3203 return; 3204 } 3205 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3206 if (!onlyRecursive || p.second) { 3207 p.first.onFragmentSaveInstanceState(this, f, outState); 3208 } 3209 } 3210 } 3211 3212 void dispatchOnFragmentViewDestroyed(Fragment f, boolean onlyRecursive) { 3213 if (mParent != null) { 3214 FragmentManager parentManager = mParent.getFragmentManager(); 3215 if (parentManager instanceof FragmentManagerImpl) { 3216 ((FragmentManagerImpl) parentManager) 3217 .dispatchOnFragmentViewDestroyed(f, true); 3218 } 3219 } 3220 if (mLifecycleCallbacks == null) { 3221 return; 3222 } 3223 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3224 if (!onlyRecursive || p.second) { 3225 p.first.onFragmentViewDestroyed(this, f); 3226 } 3227 } 3228 } 3229 3230 void dispatchOnFragmentDestroyed(Fragment f, boolean onlyRecursive) { 3231 if (mParent != null) { 3232 FragmentManager parentManager = mParent.getFragmentManager(); 3233 if (parentManager instanceof FragmentManagerImpl) { 3234 ((FragmentManagerImpl) parentManager) 3235 .dispatchOnFragmentDestroyed(f, true); 3236 } 3237 } 3238 if (mLifecycleCallbacks == null) { 3239 return; 3240 } 3241 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3242 if (!onlyRecursive || p.second) { 3243 p.first.onFragmentDestroyed(this, f); 3244 } 3245 } 3246 } 3247 3248 void dispatchOnFragmentDetached(Fragment f, boolean onlyRecursive) { 3249 if (mParent != null) { 3250 FragmentManager parentManager = mParent.getFragmentManager(); 3251 if (parentManager instanceof FragmentManagerImpl) { 3252 ((FragmentManagerImpl) parentManager) 3253 .dispatchOnFragmentDetached(f, true); 3254 } 3255 } 3256 if (mLifecycleCallbacks == null) { 3257 return; 3258 } 3259 for (Pair<FragmentLifecycleCallbacks, Boolean> p : mLifecycleCallbacks) { 3260 if (!onlyRecursive || p.second) { 3261 p.first.onFragmentDetached(this, f); 3262 } 3263 } 3264 } 3265 3266 public static int reverseTransit(int transit) { 3267 int rev = 0; 3268 switch (transit) { 3269 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 3270 rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; 3271 break; 3272 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 3273 rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN; 3274 break; 3275 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 3276 rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE; 3277 break; 3278 } 3279 return rev; 3280 3281 } 3282 3283 public static final int ANIM_STYLE_OPEN_ENTER = 1; 3284 public static final int ANIM_STYLE_OPEN_EXIT = 2; 3285 public static final int ANIM_STYLE_CLOSE_ENTER = 3; 3286 public static final int ANIM_STYLE_CLOSE_EXIT = 4; 3287 public static final int ANIM_STYLE_FADE_ENTER = 5; 3288 public static final int ANIM_STYLE_FADE_EXIT = 6; 3289 3290 public static int transitToStyleIndex(int transit, boolean enter) { 3291 int animAttr = -1; 3292 switch (transit) { 3293 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 3294 animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT; 3295 break; 3296 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 3297 animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT; 3298 break; 3299 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 3300 animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT; 3301 break; 3302 } 3303 return animAttr; 3304 } 3305 3306 @Override 3307 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { 3308 if (!"fragment".equals(name)) { 3309 return null; 3310 } 3311 3312 String fname = attrs.getAttributeValue(null, "class"); 3313 TypedArray a = context.obtainStyledAttributes(attrs, FragmentTag.Fragment); 3314 if (fname == null) { 3315 fname = a.getString(FragmentTag.Fragment_name); 3316 } 3317 int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID); 3318 String tag = a.getString(FragmentTag.Fragment_tag); 3319 a.recycle(); 3320 3321 if (!Fragment.isSupportFragmentClass(mHost.getContext(), fname)) { 3322 // Invalid support lib fragment; let the device's framework handle it. 3323 // This will allow android.app.Fragments to do the right thing. 3324 return null; 3325 } 3326 3327 int containerId = parent != null ? parent.getId() : 0; 3328 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) { 3329 throw new IllegalArgumentException(attrs.getPositionDescription() 3330 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname); 3331 } 3332 3333 // If we restored from a previous state, we may already have 3334 // instantiated this fragment from the state and should use 3335 // that instance instead of making a new one. 3336 Fragment fragment = id != View.NO_ID ? findFragmentById(id) : null; 3337 if (fragment == null && tag != null) { 3338 fragment = findFragmentByTag(tag); 3339 } 3340 if (fragment == null && containerId != View.NO_ID) { 3341 fragment = findFragmentById(containerId); 3342 } 3343 3344 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x" 3345 + Integer.toHexString(id) + " fname=" + fname 3346 + " existing=" + fragment); 3347 if (fragment == null) { 3348 fragment = Fragment.instantiate(context, fname); 3349 fragment.mFromLayout = true; 3350 fragment.mFragmentId = id != 0 ? id : containerId; 3351 fragment.mContainerId = containerId; 3352 fragment.mTag = tag; 3353 fragment.mInLayout = true; 3354 fragment.mFragmentManager = this; 3355 fragment.mHost = mHost; 3356 fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState); 3357 addFragment(fragment, true); 3358 3359 } else if (fragment.mInLayout) { 3360 // A fragment already exists and it is not one we restored from 3361 // previous state. 3362 throw new IllegalArgumentException(attrs.getPositionDescription() 3363 + ": Duplicate id 0x" + Integer.toHexString(id) 3364 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId) 3365 + " with another fragment for " + fname); 3366 } else { 3367 // This fragment was retained from a previous instance; get it 3368 // going now. 3369 fragment.mInLayout = true; 3370 fragment.mHost = mHost; 3371 // If this fragment is newly instantiated (either right now, or 3372 // from last saved state), then give it the attributes to 3373 // initialize itself. 3374 if (!fragment.mRetaining) { 3375 fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState); 3376 } 3377 } 3378 3379 // If we haven't finished entering the CREATED state ourselves yet, 3380 // push the inflated child fragment along. 3381 if (mCurState < Fragment.CREATED && fragment.mFromLayout) { 3382 moveToState(fragment, Fragment.CREATED, 0, 0, false); 3383 } else { 3384 moveToState(fragment); 3385 } 3386 3387 if (fragment.mView == null) { 3388 throw new IllegalStateException("Fragment " + fname 3389 + " did not create a view."); 3390 } 3391 if (id != 0) { 3392 fragment.mView.setId(id); 3393 } 3394 if (fragment.mView.getTag() == null) { 3395 fragment.mView.setTag(tag); 3396 } 3397 return fragment.mView; 3398 } 3399 3400 LayoutInflaterFactory getLayoutInflaterFactory() { 3401 return this; 3402 } 3403 3404 static class FragmentTag { 3405 public static final int[] Fragment = { 3406 0x01010003, 0x010100d0, 0x010100d1 3407 }; 3408 public static final int Fragment_id = 1; 3409 public static final int Fragment_name = 0; 3410 public static final int Fragment_tag = 2; 3411 } 3412 3413 /** 3414 * An add or pop transaction to be scheduled for the UI thread. 3415 */ 3416 interface OpGenerator { 3417 /** 3418 * Generate transactions to add to {@code records} and whether or not the transaction is 3419 * an add or pop to {@code isRecordPop}. 3420 * 3421 * records and isRecordPop must be added equally so that each transaction in records 3422 * matches the boolean for whether or not it is a pop in isRecordPop. 3423 * 3424 * @param records A list to add transactions to. 3425 * @param isRecordPop A list to add whether or not the transactions added to records is 3426 * a pop transaction. 3427 * @return true if something was added or false otherwise. 3428 */ 3429 boolean generateOps(ArrayList<BackStackRecord> records, ArrayList<Boolean> isRecordPop); 3430 } 3431 3432 /** 3433 * A pop operation OpGenerator. This will be run on the UI thread and will generate the 3434 * transactions that will be popped if anything can be popped. 3435 */ 3436 private class PopBackStackState implements OpGenerator { 3437 final String mName; 3438 final int mId; 3439 final int mFlags; 3440 3441 PopBackStackState(String name, int id, int flags) { 3442 mName = name; 3443 mId = id; 3444 mFlags = flags; 3445 } 3446 3447 @Override 3448 public boolean generateOps(ArrayList<BackStackRecord> records, 3449 ArrayList<Boolean> isRecordPop) { 3450 return popBackStackState(records, isRecordPop, mName, mId, mFlags); 3451 } 3452 } 3453 3454 /** 3455 * A listener for a postponed transaction. This waits until 3456 * {@link Fragment#startPostponedEnterTransition()} is called or a transaction is started 3457 * that interacts with this one, based on interactions with the fragment container. 3458 */ 3459 static class StartEnterTransitionListener 3460 implements Fragment.OnStartEnterTransitionListener { 3461 private final boolean mIsBack; 3462 private final BackStackRecord mRecord; 3463 private int mNumPostponed; 3464 3465 StartEnterTransitionListener(BackStackRecord record, boolean isBack) { 3466 mIsBack = isBack; 3467 mRecord = record; 3468 } 3469 3470 /** 3471 * Called from {@link Fragment#startPostponedEnterTransition()}, this decreases the 3472 * number of Fragments that are postponed. This may cause the transaction to schedule 3473 * to finish running and run transitions and animations. 3474 */ 3475 @Override 3476 public void onStartEnterTransition() { 3477 mNumPostponed--; 3478 if (mNumPostponed != 0) { 3479 return; 3480 } 3481 mRecord.mManager.scheduleCommit(); 3482 } 3483 3484 /** 3485 * Called from {@link Fragment# 3486 * setOnStartEnterTransitionListener(Fragment.OnStartEnterTransitionListener)}, this 3487 * increases the number of fragments that are postponed as part of this transaction. 3488 */ 3489 @Override 3490 public void startListening() { 3491 mNumPostponed++; 3492 } 3493 3494 /** 3495 * @return true if there are no more postponed fragments as part of the transaction. 3496 */ 3497 public boolean isReady() { 3498 return mNumPostponed == 0; 3499 } 3500 3501 /** 3502 * Completes the transaction and start the animations and transitions. This may skip 3503 * the transitions if this is called before all fragments have called 3504 * {@link Fragment#startPostponedEnterTransition()}. 3505 */ 3506 public void completeTransaction() { 3507 final boolean canceled; 3508 canceled = mNumPostponed > 0; 3509 FragmentManagerImpl manager = mRecord.mManager; 3510 final int numAdded = manager.mAdded.size(); 3511 for (int i = 0; i < numAdded; i++) { 3512 final Fragment fragment = manager.mAdded.get(i); 3513 fragment.setOnStartEnterTransitionListener(null); 3514 if (canceled && fragment.isPostponed()) { 3515 fragment.startPostponedEnterTransition(); 3516 } 3517 } 3518 mRecord.mManager.completeExecute(mRecord, mIsBack, !canceled, true); 3519 } 3520 3521 /** 3522 * Cancels this transaction instead of completing it. That means that the state isn't 3523 * changed, so the pop results in no change to the state. 3524 */ 3525 public void cancelTransaction() { 3526 mRecord.mManager.completeExecute(mRecord, mIsBack, false, false); 3527 } 3528 } 3529} 3530