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