FragmentManager.java revision 3a1a7fff9873abbf8097c96f7654a459bf34f223
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 android.content.Context; 20import android.content.res.Configuration; 21import android.os.Bundle; 22import android.os.Handler; 23import android.os.Looper; 24import android.os.Parcel; 25import android.os.Parcelable; 26import android.support.v4.util.DebugUtils; 27import android.support.v4.util.LogWriter; 28import android.util.Log; 29import android.util.SparseArray; 30import android.view.animation.AccelerateInterpolator; 31import android.view.animation.AlphaAnimation; 32import android.view.animation.Animation; 33import android.view.animation.AnimationSet; 34import android.view.animation.AnimationUtils; 35import android.view.animation.DecelerateInterpolator; 36import android.view.animation.Interpolator; 37import android.view.animation.ScaleAnimation; 38import android.view.animation.Animation.AnimationListener; 39import android.view.Menu; 40import android.view.MenuInflater; 41import android.view.MenuItem; 42import android.view.View; 43import android.view.ViewGroup; 44 45import java.io.FileDescriptor; 46import java.io.PrintWriter; 47import java.util.ArrayList; 48import java.util.Arrays; 49import java.util.List; 50 51/** 52 * Static library support version of the framework's {@link android.app.FragmentManager}. 53 * Used to write apps that run on platforms prior to Android 3.0. When running 54 * on Android 3.0 or above, this implementation is still used; it does not try 55 * to switch to the framework's implementation. See the framework SDK 56 * documentation for a class overview. 57 * 58 * <p>Your activity must derive from {@link FragmentActivity} to use this. 59 */ 60public abstract class FragmentManager { 61 /** 62 * Representation of an entry on the fragment back stack, as created 63 * with {@link FragmentTransaction#addToBackStack(String) 64 * FragmentTransaction.addToBackStack()}. Entries can later be 65 * retrieved with {@link FragmentManager#getBackStackEntryAt(int) 66 * FragmentManager.getBackStackEntry()}. 67 * 68 * <p>Note that you should never hold on to a BackStackEntry object; 69 * the identifier as returned by {@link #getId} is the only thing that 70 * will be persisted across activity instances. 71 */ 72 public interface BackStackEntry { 73 /** 74 * Return the unique identifier for the entry. This is the only 75 * representation of the entry that will persist across activity 76 * instances. 77 */ 78 public int getId(); 79 80 /** 81 * Get the name that was supplied to 82 * {@link FragmentTransaction#addToBackStack(String) 83 * FragmentTransaction.addToBackStack(String)} when creating this entry. 84 */ 85 public String getName(); 86 87 /** 88 * Return the full bread crumb title resource identifier for the entry, 89 * or 0 if it does not have one. 90 */ 91 public int getBreadCrumbTitleRes(); 92 93 /** 94 * Return the short bread crumb title resource identifier for the entry, 95 * or 0 if it does not have one. 96 */ 97 public int getBreadCrumbShortTitleRes(); 98 99 /** 100 * Return the full bread crumb title for the entry, or null if it 101 * does not have one. 102 */ 103 public CharSequence getBreadCrumbTitle(); 104 105 /** 106 * Return the short bread crumb title for the entry, or null if it 107 * does not have one. 108 */ 109 public CharSequence getBreadCrumbShortTitle(); 110 } 111 112 /** 113 * Interface to watch for changes to the back stack. 114 */ 115 public interface OnBackStackChangedListener { 116 /** 117 * Called whenever the contents of the back stack change. 118 */ 119 public void onBackStackChanged(); 120 } 121 122 /** 123 * Start a series of edit operations on the Fragments associated with 124 * this FragmentManager. 125 * 126 * <p>Note: A fragment transaction can only be created/committed prior 127 * to an activity saving its state. If you try to commit a transaction 128 * after {@link FragmentActivity#onSaveInstanceState FragmentActivity.onSaveInstanceState()} 129 * (and prior to a following {@link FragmentActivity#onStart FragmentActivity.onStart} 130 * or {@link FragmentActivity#onResume FragmentActivity.onResume()}, you will get an error. 131 * This is because the framework takes care of saving your current fragments 132 * in the state, and if changes are made after the state is saved then they 133 * will be lost.</p> 134 */ 135 public abstract FragmentTransaction beginTransaction(); 136 137 /** @hide -- remove once prebuilts are in. */ 138 @Deprecated 139 public FragmentTransaction openTransaction() { 140 return beginTransaction(); 141 } 142 143 /** 144 * After a {@link FragmentTransaction} is committed with 145 * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it 146 * is scheduled to be executed asynchronously on the process's main thread. 147 * If you want to immediately executing any such pending operations, you 148 * can call this function (only from the main thread) to do so. Note that 149 * all callbacks and other related behavior will be done from within this 150 * call, so be careful about where this is called from. 151 * 152 * @return Returns true if there were any pending transactions to be 153 * executed. 154 */ 155 public abstract boolean executePendingTransactions(); 156 157 /** 158 * Finds a fragment that was identified by the given id either when inflated 159 * from XML or as the container ID when added in a transaction. This first 160 * searches through fragments that are currently added to the manager's 161 * activity; if no such fragment is found, then all fragments currently 162 * on the back stack associated with this ID are searched. 163 * @return The fragment if found or null otherwise. 164 */ 165 public abstract Fragment findFragmentById(int id); 166 167 /** 168 * Finds a fragment that was identified by the given tag either when inflated 169 * from XML or as supplied when added in a transaction. This first 170 * searches through fragments that are currently added to the manager's 171 * activity; if no such fragment is found, then all fragments currently 172 * on the back stack are searched. 173 * @return The fragment if found or null otherwise. 174 */ 175 public abstract Fragment findFragmentByTag(String tag); 176 177 /** 178 * Flag for {@link #popBackStack(String, int)} 179 * and {@link #popBackStack(int, int)}: If set, and the name or ID of 180 * a back stack entry has been supplied, then all matching entries will 181 * be consumed until one that doesn't match is found or the bottom of 182 * the stack is reached. Otherwise, all entries up to but not including that entry 183 * will be removed. 184 */ 185 public static final int POP_BACK_STACK_INCLUSIVE = 1<<0; 186 187 /** 188 * Pop the top state off the back stack. Returns true if there was one 189 * to pop, else false. This function is asynchronous -- it enqueues the 190 * request to pop, but the action will not be performed until the application 191 * returns to its event loop. 192 */ 193 public abstract void popBackStack(); 194 195 /** 196 * Like {@link #popBackStack()}, but performs the operation immediately 197 * inside of the call. This is like calling {@link #executePendingTransactions()} 198 * afterwards. 199 * @return Returns true if there was something popped, else false. 200 */ 201 public abstract boolean popBackStackImmediate(); 202 203 /** 204 * Pop the last fragment transition from the manager's fragment 205 * back stack. If there is nothing to pop, false is returned. 206 * This function is asynchronous -- it enqueues the 207 * request to pop, but the action will not be performed until the application 208 * returns to its event loop. 209 * 210 * @param name If non-null, this is the name of a previous back state 211 * to look for; if found, all states up to that state will be popped. The 212 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether 213 * the named state itself is popped. If null, only the top state is popped. 214 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. 215 */ 216 public abstract void popBackStack(String name, int flags); 217 218 /** 219 * Like {@link #popBackStack(String, int)}, but performs the operation immediately 220 * inside of the call. This is like calling {@link #executePendingTransactions()} 221 * afterwards. 222 * @return Returns true if there was something popped, else false. 223 */ 224 public abstract boolean popBackStackImmediate(String name, int flags); 225 226 /** 227 * Pop all back stack states up to the one with the given identifier. 228 * This function is asynchronous -- it enqueues the 229 * request to pop, but the action will not be performed until the application 230 * returns to its event loop. 231 * 232 * @param id Identifier of the stated to be popped. If no identifier exists, 233 * false is returned. 234 * The identifier is the number returned by 235 * {@link FragmentTransaction#commit() FragmentTransaction.commit()}. The 236 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether 237 * the named state itself is popped. 238 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. 239 */ 240 public abstract void popBackStack(int id, int flags); 241 242 /** 243 * Like {@link #popBackStack(int, int)}, but performs the operation immediately 244 * inside of the call. This is like calling {@link #executePendingTransactions()} 245 * afterwards. 246 * @return Returns true if there was something popped, else false. 247 */ 248 public abstract boolean popBackStackImmediate(int id, int flags); 249 250 /** 251 * Return the number of entries currently in the back stack. 252 */ 253 public abstract int getBackStackEntryCount(); 254 255 /** 256 * Return the BackStackEntry at index <var>index</var> in the back stack; 257 * entries start index 0 being the bottom of the stack. 258 */ 259 public abstract BackStackEntry getBackStackEntryAt(int index); 260 261 /** 262 * Add a new listener for changes to the fragment back stack. 263 */ 264 public abstract void addOnBackStackChangedListener(OnBackStackChangedListener listener); 265 266 /** 267 * Remove a listener that was previously added with 268 * {@link #addOnBackStackChangedListener(OnBackStackChangedListener)}. 269 */ 270 public abstract void removeOnBackStackChangedListener(OnBackStackChangedListener listener); 271 272 /** 273 * Put a reference to a fragment in a Bundle. This Bundle can be 274 * persisted as saved state, and when later restoring 275 * {@link #getFragment(Bundle, String)} will return the current 276 * instance of the same fragment. 277 * 278 * @param bundle The bundle in which to put the fragment reference. 279 * @param key The name of the entry in the bundle. 280 * @param fragment The Fragment whose reference is to be stored. 281 */ 282 public abstract void putFragment(Bundle bundle, String key, Fragment fragment); 283 284 /** 285 * Retrieve the current Fragment instance for a reference previously 286 * placed with {@link #putFragment(Bundle, String, Fragment)}. 287 * 288 * @param bundle The bundle from which to retrieve the fragment reference. 289 * @param key The name of the entry in the bundle. 290 * @return Returns the current Fragment instance that is associated with 291 * the given reference. 292 */ 293 public abstract Fragment getFragment(Bundle bundle, String key); 294 295 /** 296 * Get a list of all fragments that have been added to the fragment manager. 297 * 298 * @return The list of all fragments or null if none. 299 * @hide 300 */ 301 public abstract List<Fragment> getFragments(); 302 303 /** 304 * Save the current instance state of the given Fragment. This can be 305 * used later when creating a new instance of the Fragment and adding 306 * it to the fragment manager, to have it create itself to match the 307 * current state returned here. Note that there are limits on how 308 * this can be used: 309 * 310 * <ul> 311 * <li>The Fragment must currently be attached to the FragmentManager. 312 * <li>A new Fragment created using this saved state must be the same class 313 * type as the Fragment it was created from. 314 * <li>The saved state can not contain dependencies on other fragments -- 315 * that is it can't use {@link #putFragment(Bundle, String, Fragment)} to 316 * store a fragment reference because that reference may not be valid when 317 * this saved state is later used. Likewise the Fragment's target and 318 * result code are not included in this state. 319 * </ul> 320 * 321 * @param f The Fragment whose state is to be saved. 322 * @return The generated state. This will be null if there was no 323 * interesting state created by the fragment. 324 */ 325 public abstract Fragment.SavedState saveFragmentInstanceState(Fragment f); 326 327 /** 328 * Print the FragmentManager's state into the given stream. 329 * 330 * @param prefix Text to print at the front of each line. 331 * @param fd The raw file descriptor that the dump is being sent to. 332 * @param writer A PrintWriter to which the dump is to be set. 333 * @param args Additional arguments to the dump request. 334 */ 335 public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args); 336 337 /** 338 * Control whether the framework's internal fragment manager debugging 339 * logs are turned on. If enabled, you will see output in logcat as 340 * the framework performs fragment operations. 341 */ 342 public static void enableDebugLogging(boolean enabled) { 343 FragmentManagerImpl.DEBUG = enabled; 344 } 345} 346 347final class FragmentManagerState implements Parcelable { 348 FragmentState[] mActive; 349 int[] mAdded; 350 BackStackState[] mBackStack; 351 352 public FragmentManagerState() { 353 } 354 355 public FragmentManagerState(Parcel in) { 356 mActive = in.createTypedArray(FragmentState.CREATOR); 357 mAdded = in.createIntArray(); 358 mBackStack = in.createTypedArray(BackStackState.CREATOR); 359 } 360 361 public int describeContents() { 362 return 0; 363 } 364 365 public void writeToParcel(Parcel dest, int flags) { 366 dest.writeTypedArray(mActive, flags); 367 dest.writeIntArray(mAdded); 368 dest.writeTypedArray(mBackStack, flags); 369 } 370 371 public static final Parcelable.Creator<FragmentManagerState> CREATOR 372 = new Parcelable.Creator<FragmentManagerState>() { 373 public FragmentManagerState createFromParcel(Parcel in) { 374 return new FragmentManagerState(in); 375 } 376 377 public FragmentManagerState[] newArray(int size) { 378 return new FragmentManagerState[size]; 379 } 380 }; 381} 382 383/** 384 * Callbacks from FragmentManagerImpl to its container. 385 */ 386interface FragmentContainer { 387 public View findViewById(int id); 388} 389 390/** 391 * Container for fragments associated with an activity. 392 */ 393final class FragmentManagerImpl extends FragmentManager { 394 static boolean DEBUG = false; 395 static final String TAG = "FragmentManager"; 396 397 static final boolean HONEYCOMB = android.os.Build.VERSION.SDK_INT >= 11; 398 399 static final String TARGET_REQUEST_CODE_STATE_TAG = "android:target_req_state"; 400 static final String TARGET_STATE_TAG = "android:target_state"; 401 static final String VIEW_STATE_TAG = "android:view_state"; 402 static final String USER_VISIBLE_HINT_TAG = "android:user_visible_hint"; 403 404 ArrayList<Runnable> mPendingActions; 405 Runnable[] mTmpActions; 406 boolean mExecutingActions; 407 408 ArrayList<Fragment> mActive; 409 ArrayList<Fragment> mAdded; 410 ArrayList<Integer> mAvailIndices; 411 ArrayList<BackStackRecord> mBackStack; 412 ArrayList<Fragment> mCreatedMenus; 413 414 // Must be accessed while locked. 415 ArrayList<BackStackRecord> mBackStackIndices; 416 ArrayList<Integer> mAvailBackStackIndices; 417 418 ArrayList<OnBackStackChangedListener> mBackStackChangeListeners; 419 420 int mCurState = Fragment.INITIALIZING; 421 FragmentActivity mActivity; 422 FragmentContainer mContainer; 423 Fragment mParent; 424 425 boolean mNeedMenuInvalidate; 426 boolean mStateSaved; 427 boolean mDestroyed; 428 String mNoTransactionsBecause; 429 boolean mHavePendingDeferredStart; 430 431 // Temporary vars for state save and restore. 432 Bundle mStateBundle = null; 433 SparseArray<Parcelable> mStateArray = null; 434 435 Runnable mExecCommit = new Runnable() { 436 @Override 437 public void run() { 438 execPendingActions(); 439 } 440 }; 441 442 private void throwException(RuntimeException ex) { 443 Log.e(TAG, ex.getMessage()); 444 Log.e(TAG, "Activity state:"); 445 LogWriter logw = new LogWriter(TAG); 446 PrintWriter pw = new PrintWriter(logw); 447 if (mActivity != null) { 448 try { 449 mActivity.dump(" ", null, pw, new String[] { }); 450 } catch (Exception e) { 451 Log.e(TAG, "Failed dumping state", e); 452 } 453 } else { 454 try { 455 dump(" ", null, pw, new String[] { }); 456 } catch (Exception e) { 457 Log.e(TAG, "Failed dumping state", e); 458 } 459 } 460 throw ex; 461 } 462 463 @Override 464 public FragmentTransaction beginTransaction() { 465 return new BackStackRecord(this); 466 } 467 468 @Override 469 public boolean executePendingTransactions() { 470 return execPendingActions(); 471 } 472 473 @Override 474 public void popBackStack() { 475 enqueueAction(new Runnable() { 476 @Override public void run() { 477 popBackStackState(mActivity.mHandler, null, -1, 0); 478 } 479 }, false); 480 } 481 482 @Override 483 public boolean popBackStackImmediate() { 484 checkStateLoss(); 485 executePendingTransactions(); 486 return popBackStackState(mActivity.mHandler, null, -1, 0); 487 } 488 489 @Override 490 public void popBackStack(final String name, final int flags) { 491 enqueueAction(new Runnable() { 492 @Override public void run() { 493 popBackStackState(mActivity.mHandler, name, -1, flags); 494 } 495 }, false); 496 } 497 498 @Override 499 public boolean popBackStackImmediate(String name, int flags) { 500 checkStateLoss(); 501 executePendingTransactions(); 502 return popBackStackState(mActivity.mHandler, name, -1, flags); 503 } 504 505 @Override 506 public void popBackStack(final int id, final int flags) { 507 if (id < 0) { 508 throw new IllegalArgumentException("Bad id: " + id); 509 } 510 enqueueAction(new Runnable() { 511 @Override public void run() { 512 popBackStackState(mActivity.mHandler, null, id, flags); 513 } 514 }, false); 515 } 516 517 @Override 518 public boolean popBackStackImmediate(int id, int flags) { 519 checkStateLoss(); 520 executePendingTransactions(); 521 if (id < 0) { 522 throw new IllegalArgumentException("Bad id: " + id); 523 } 524 return popBackStackState(mActivity.mHandler, null, id, flags); 525 } 526 527 @Override 528 public int getBackStackEntryCount() { 529 return mBackStack != null ? mBackStack.size() : 0; 530 } 531 532 @Override 533 public BackStackEntry getBackStackEntryAt(int index) { 534 return mBackStack.get(index); 535 } 536 537 @Override 538 public void addOnBackStackChangedListener(OnBackStackChangedListener listener) { 539 if (mBackStackChangeListeners == null) { 540 mBackStackChangeListeners = new ArrayList<OnBackStackChangedListener>(); 541 } 542 mBackStackChangeListeners.add(listener); 543 } 544 545 @Override 546 public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) { 547 if (mBackStackChangeListeners != null) { 548 mBackStackChangeListeners.remove(listener); 549 } 550 } 551 552 @Override 553 public void putFragment(Bundle bundle, String key, Fragment fragment) { 554 if (fragment.mIndex < 0) { 555 throwException(new IllegalStateException("Fragment " + fragment 556 + " is not currently in the FragmentManager")); 557 } 558 bundle.putInt(key, fragment.mIndex); 559 } 560 561 @Override 562 public Fragment getFragment(Bundle bundle, String key) { 563 int index = bundle.getInt(key, -1); 564 if (index == -1) { 565 return null; 566 } 567 if (index >= mActive.size()) { 568 throwException(new IllegalStateException("Fragement no longer exists for key " 569 + key + ": index " + index)); 570 } 571 Fragment f = mActive.get(index); 572 if (f == null) { 573 throwException(new IllegalStateException("Fragement no longer exists for key " 574 + key + ": index " + index)); 575 } 576 return f; 577 } 578 579 @Override 580 public List<Fragment> getFragments() { 581 return mActive; 582 } 583 584 @Override 585 public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) { 586 if (fragment.mIndex < 0) { 587 throwException( new IllegalStateException("Fragment " + fragment 588 + " is not currently in the FragmentManager")); 589 } 590 if (fragment.mState > Fragment.INITIALIZING) { 591 Bundle result = saveFragmentBasicState(fragment); 592 return result != null ? new Fragment.SavedState(result) : null; 593 } 594 return null; 595 } 596 597 @Override 598 public String toString() { 599 StringBuilder sb = new StringBuilder(128); 600 sb.append("FragmentManager{"); 601 sb.append(Integer.toHexString(System.identityHashCode(this))); 602 sb.append(" in "); 603 if (mParent != null) { 604 DebugUtils.buildShortClassTag(mParent, sb); 605 } else { 606 DebugUtils.buildShortClassTag(mActivity, sb); 607 } 608 sb.append("}}"); 609 return sb.toString(); 610 } 611 612 @Override 613 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 614 String innerPrefix = prefix + " "; 615 616 int N; 617 if (mActive != null) { 618 N = mActive.size(); 619 if (N > 0) { 620 writer.print(prefix); writer.print("Active Fragments in "); 621 writer.print(Integer.toHexString(System.identityHashCode(this))); 622 writer.println(":"); 623 for (int i=0; i<N; i++) { 624 Fragment f = mActive.get(i); 625 writer.print(prefix); writer.print(" #"); writer.print(i); 626 writer.print(": "); writer.println(f); 627 if (f != null) { 628 f.dump(innerPrefix, fd, writer, args); 629 } 630 } 631 } 632 } 633 634 if (mAdded != null) { 635 N = mAdded.size(); 636 if (N > 0) { 637 writer.print(prefix); writer.println("Added Fragments:"); 638 for (int i=0; i<N; i++) { 639 Fragment f = mAdded.get(i); 640 writer.print(prefix); writer.print(" #"); writer.print(i); 641 writer.print(": "); writer.println(f.toString()); 642 } 643 } 644 } 645 646 if (mCreatedMenus != null) { 647 N = mCreatedMenus.size(); 648 if (N > 0) { 649 writer.print(prefix); writer.println("Fragments Created Menus:"); 650 for (int i=0; i<N; i++) { 651 Fragment f = mCreatedMenus.get(i); 652 writer.print(prefix); writer.print(" #"); writer.print(i); 653 writer.print(": "); writer.println(f.toString()); 654 } 655 } 656 } 657 658 if (mBackStack != null) { 659 N = mBackStack.size(); 660 if (N > 0) { 661 writer.print(prefix); writer.println("Back Stack:"); 662 for (int i=0; i<N; i++) { 663 BackStackRecord bs = mBackStack.get(i); 664 writer.print(prefix); writer.print(" #"); writer.print(i); 665 writer.print(": "); writer.println(bs.toString()); 666 bs.dump(innerPrefix, fd, writer, args); 667 } 668 } 669 } 670 671 synchronized (this) { 672 if (mBackStackIndices != null) { 673 N = mBackStackIndices.size(); 674 if (N > 0) { 675 writer.print(prefix); writer.println("Back Stack Indices:"); 676 for (int i=0; i<N; i++) { 677 BackStackRecord bs = mBackStackIndices.get(i); 678 writer.print(prefix); writer.print(" #"); writer.print(i); 679 writer.print(": "); writer.println(bs); 680 } 681 } 682 } 683 684 if (mAvailBackStackIndices != null && mAvailBackStackIndices.size() > 0) { 685 writer.print(prefix); writer.print("mAvailBackStackIndices: "); 686 writer.println(Arrays.toString(mAvailBackStackIndices.toArray())); 687 } 688 } 689 690 if (mPendingActions != null) { 691 N = mPendingActions.size(); 692 if (N > 0) { 693 writer.print(prefix); writer.println("Pending Actions:"); 694 for (int i=0; i<N; i++) { 695 Runnable r = mPendingActions.get(i); 696 writer.print(prefix); writer.print(" #"); writer.print(i); 697 writer.print(": "); writer.println(r); 698 } 699 } 700 } 701 702 writer.print(prefix); writer.println("FragmentManager misc state:"); 703 writer.print(prefix); writer.print(" mActivity="); writer.println(mActivity); 704 writer.print(prefix); writer.print(" mContainer="); writer.println(mContainer); 705 if (mParent != null) { 706 writer.print(prefix); writer.print(" mParent="); writer.println(mParent); 707 } 708 writer.print(prefix); writer.print(" mCurState="); writer.print(mCurState); 709 writer.print(" mStateSaved="); writer.print(mStateSaved); 710 writer.print(" mDestroyed="); writer.println(mDestroyed); 711 if (mNeedMenuInvalidate) { 712 writer.print(prefix); writer.print(" mNeedMenuInvalidate="); 713 writer.println(mNeedMenuInvalidate); 714 } 715 if (mNoTransactionsBecause != null) { 716 writer.print(prefix); writer.print(" mNoTransactionsBecause="); 717 writer.println(mNoTransactionsBecause); 718 } 719 if (mAvailIndices != null && mAvailIndices.size() > 0) { 720 writer.print(prefix); writer.print(" mAvailIndices: "); 721 writer.println(Arrays.toString(mAvailIndices.toArray())); 722 } 723 } 724 725 static final Interpolator DECELERATE_QUINT = new DecelerateInterpolator(2.5f); 726 static final Interpolator DECELERATE_CUBIC = new DecelerateInterpolator(1.5f); 727 static final Interpolator ACCELERATE_QUINT = new AccelerateInterpolator(2.5f); 728 static final Interpolator ACCELERATE_CUBIC = new AccelerateInterpolator(1.5f); 729 730 static final int ANIM_DUR = 220; 731 732 static Animation makeOpenCloseAnimation(Context context, float startScale, 733 float endScale, float startAlpha, float endAlpha) { 734 AnimationSet set = new AnimationSet(false); 735 ScaleAnimation scale = new ScaleAnimation(startScale, endScale, startScale, endScale, 736 Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f); 737 scale.setInterpolator(DECELERATE_QUINT); 738 scale.setDuration(ANIM_DUR); 739 set.addAnimation(scale); 740 AlphaAnimation alpha = new AlphaAnimation(startAlpha, endAlpha); 741 alpha.setInterpolator(DECELERATE_CUBIC); 742 alpha.setDuration(ANIM_DUR); 743 set.addAnimation(alpha); 744 return set; 745 } 746 747 static Animation makeFadeAnimation(Context context, float start, float end) { 748 AlphaAnimation anim = new AlphaAnimation(start, end); 749 anim.setInterpolator(DECELERATE_CUBIC); 750 anim.setDuration(ANIM_DUR); 751 return anim; 752 } 753 754 Animation loadAnimation(Fragment fragment, int transit, boolean enter, 755 int transitionStyle) { 756 Animation animObj = fragment.onCreateAnimation(transit, enter, 757 fragment.mNextAnim); 758 if (animObj != null) { 759 return animObj; 760 } 761 762 if (fragment.mNextAnim != 0) { 763 Animation anim = AnimationUtils.loadAnimation(mActivity, fragment.mNextAnim); 764 if (anim != null) { 765 return anim; 766 } 767 } 768 769 if (transit == 0) { 770 return null; 771 } 772 773 int styleIndex = transitToStyleIndex(transit, enter); 774 if (styleIndex < 0) { 775 return null; 776 } 777 778 switch (styleIndex) { 779 case ANIM_STYLE_OPEN_ENTER: 780 return makeOpenCloseAnimation(mActivity, 1.125f, 1.0f, 0, 1); 781 case ANIM_STYLE_OPEN_EXIT: 782 return makeOpenCloseAnimation(mActivity, 1.0f, .975f, 1, 0); 783 case ANIM_STYLE_CLOSE_ENTER: 784 return makeOpenCloseAnimation(mActivity, .975f, 1.0f, 0, 1); 785 case ANIM_STYLE_CLOSE_EXIT: 786 return makeOpenCloseAnimation(mActivity, 1.0f, 1.075f, 1, 0); 787 case ANIM_STYLE_FADE_ENTER: 788 return makeFadeAnimation(mActivity, 0, 1); 789 case ANIM_STYLE_FADE_EXIT: 790 return makeFadeAnimation(mActivity, 1, 0); 791 } 792 793 if (transitionStyle == 0 && mActivity.getWindow() != null) { 794 transitionStyle = mActivity.getWindow().getAttributes().windowAnimations; 795 } 796 if (transitionStyle == 0) { 797 return null; 798 } 799 800 //TypedArray attrs = mActivity.obtainStyledAttributes(transitionStyle, 801 // com.android.internal.R.styleable.FragmentAnimation); 802 //int anim = attrs.getResourceId(styleIndex, 0); 803 //attrs.recycle(); 804 805 //if (anim == 0) { 806 // return null; 807 //} 808 809 //return AnimatorInflater.loadAnimator(mActivity, anim); 810 return null; 811 } 812 813 public void performPendingDeferredStart(Fragment f) { 814 if (f.mDeferStart) { 815 if (mExecutingActions) { 816 // Wait until we're done executing our pending transactions 817 mHavePendingDeferredStart = true; 818 return; 819 } 820 f.mDeferStart = false; 821 moveToState(f, mCurState, 0, 0, false); 822 } 823 } 824 825 void moveToState(Fragment f, int newState, int transit, int transitionStyle, 826 boolean keepActive) { 827 // Fragments that are not currently added will sit in the onCreate() state. 828 if ((!f.mAdded || f.mDetached) && newState > Fragment.CREATED) { 829 newState = Fragment.CREATED; 830 } 831 if (f.mRemoving && newState > f.mState) { 832 // While removing a fragment, we can't change it to a higher state. 833 newState = f.mState; 834 } 835 // Defer start if requested; don't allow it to move to STARTED or higher 836 // if it's not already started. 837 if (f.mDeferStart && f.mState < Fragment.STARTED && newState > Fragment.STOPPED) { 838 newState = Fragment.STOPPED; 839 } 840 if (f.mState < newState) { 841 // For fragments that are created from a layout, when restoring from 842 // state we don't want to allow them to be created until they are 843 // being reloaded from the layout. 844 if (f.mFromLayout && !f.mInLayout) { 845 return; 846 } 847 if (f.mAnimatingAway != null) { 848 // The fragment is currently being animated... but! Now we 849 // want to move our state back up. Give up on waiting for the 850 // animation, move to whatever the final state should be once 851 // the animation is done, and then we can proceed from there. 852 f.mAnimatingAway = null; 853 moveToState(f, f.mStateAfterAnimating, 0, 0, true); 854 } 855 switch (f.mState) { 856 case Fragment.INITIALIZING: 857 if (DEBUG) Log.v(TAG, "moveto CREATED: " + f); 858 if (f.mSavedFragmentState != null) { 859 f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray( 860 FragmentManagerImpl.VIEW_STATE_TAG); 861 f.mTarget = getFragment(f.mSavedFragmentState, 862 FragmentManagerImpl.TARGET_STATE_TAG); 863 if (f.mTarget != null) { 864 f.mTargetRequestCode = f.mSavedFragmentState.getInt( 865 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0); 866 } 867 f.mUserVisibleHint = f.mSavedFragmentState.getBoolean( 868 FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true); 869 if (!f.mUserVisibleHint) { 870 f.mDeferStart = true; 871 if (newState > Fragment.STOPPED) { 872 newState = Fragment.STOPPED; 873 } 874 } 875 } 876 f.mActivity = mActivity; 877 f.mParentFragment = mParent; 878 f.mFragmentManager = mParent != null 879 ? mParent.mChildFragmentManager : mActivity.mFragments; 880 f.mCalled = false; 881 f.onAttach(mActivity); 882 if (!f.mCalled) { 883 throw new SuperNotCalledException("Fragment " + f 884 + " did not call through to super.onAttach()"); 885 } 886 if (f.mParentFragment == null) { 887 mActivity.onAttachFragment(f); 888 } 889 890 if (!f.mRetaining) { 891 f.performCreate(f.mSavedFragmentState); 892 } 893 f.mRetaining = false; 894 if (f.mFromLayout) { 895 // For fragments that are part of the content view 896 // layout, we need to instantiate the view immediately 897 // and the inflater will take care of adding it. 898 f.mView = f.performCreateView(f.getLayoutInflater( 899 f.mSavedFragmentState), null, f.mSavedFragmentState); 900 if (f.mView != null) { 901 f.mInnerView = f.mView; 902 f.mView = NoSaveStateFrameLayout.wrap(f.mView); 903 if (f.mHidden) f.mView.setVisibility(View.GONE); 904 f.onViewCreated(f.mView, f.mSavedFragmentState); 905 } else { 906 f.mInnerView = null; 907 } 908 } 909 case Fragment.CREATED: 910 if (newState > Fragment.CREATED) { 911 if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f); 912 if (!f.mFromLayout) { 913 ViewGroup container = null; 914 if (f.mContainerId != 0) { 915 container = (ViewGroup)mContainer.findViewById(f.mContainerId); 916 if (container == null && !f.mRestored) { 917 throwException(new IllegalArgumentException( 918 "No view found for id 0x" 919 + Integer.toHexString(f.mContainerId) + " (" 920 + f.getResources().getResourceName(f.mContainerId) 921 + ") for fragment " + f)); 922 } 923 } 924 f.mContainer = container; 925 f.mView = f.performCreateView(f.getLayoutInflater( 926 f.mSavedFragmentState), container, f.mSavedFragmentState); 927 if (f.mView != null) { 928 f.mInnerView = f.mView; 929 f.mView = NoSaveStateFrameLayout.wrap(f.mView); 930 if (container != null) { 931 Animation anim = loadAnimation(f, transit, true, 932 transitionStyle); 933 if (anim != null) { 934 f.mView.startAnimation(anim); 935 } 936 container.addView(f.mView); 937 } 938 if (f.mHidden) f.mView.setVisibility(View.GONE); 939 f.onViewCreated(f.mView, f.mSavedFragmentState); 940 } else { 941 f.mInnerView = null; 942 } 943 } 944 945 f.performActivityCreated(f.mSavedFragmentState); 946 if (f.mView != null) { 947 f.restoreViewState(f.mSavedFragmentState); 948 } 949 f.mSavedFragmentState = null; 950 } 951 case Fragment.ACTIVITY_CREATED: 952 case Fragment.STOPPED: 953 if (newState > Fragment.STOPPED) { 954 if (DEBUG) Log.v(TAG, "moveto STARTED: " + f); 955 f.performStart(); 956 } 957 case Fragment.STARTED: 958 if (newState > Fragment.STARTED) { 959 if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f); 960 f.mResumed = true; 961 f.performResume(); 962 f.mSavedFragmentState = null; 963 f.mSavedViewState = null; 964 } 965 } 966 } else if (f.mState > newState) { 967 switch (f.mState) { 968 case Fragment.RESUMED: 969 if (newState < Fragment.RESUMED) { 970 if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f); 971 f.performPause(); 972 f.mResumed = false; 973 } 974 case Fragment.STARTED: 975 if (newState < Fragment.STARTED) { 976 if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f); 977 f.performStop(); 978 } 979 case Fragment.STOPPED: 980 if (newState < Fragment.STOPPED) { 981 if (DEBUG) Log.v(TAG, "movefrom STOPPED: " + f); 982 f.performReallyStop(); 983 } 984 case Fragment.ACTIVITY_CREATED: 985 if (newState < Fragment.ACTIVITY_CREATED) { 986 if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f); 987 if (f.mView != null) { 988 // Need to save the current view state if not 989 // done already. 990 if (!mActivity.isFinishing() && f.mSavedViewState == null) { 991 saveFragmentViewState(f); 992 } 993 } 994 f.performDestroyView(); 995 if (f.mView != null && f.mContainer != null) { 996 Animation anim = null; 997 if (mCurState > Fragment.INITIALIZING && !mDestroyed) { 998 anim = loadAnimation(f, transit, false, 999 transitionStyle); 1000 } 1001 if (anim != null) { 1002 final Fragment fragment = f; 1003 f.mAnimatingAway = f.mView; 1004 f.mStateAfterAnimating = newState; 1005 anim.setAnimationListener(new AnimationListener() { 1006 @Override 1007 public void onAnimationEnd(Animation animation) { 1008 if (fragment.mAnimatingAway != null) { 1009 fragment.mAnimatingAway = null; 1010 moveToState(fragment, fragment.mStateAfterAnimating, 1011 0, 0, false); 1012 } 1013 } 1014 @Override 1015 public void onAnimationRepeat(Animation animation) { 1016 } 1017 @Override 1018 public void onAnimationStart(Animation animation) { 1019 } 1020 }); 1021 f.mView.startAnimation(anim); 1022 } 1023 f.mContainer.removeView(f.mView); 1024 } 1025 f.mContainer = null; 1026 f.mView = null; 1027 f.mInnerView = null; 1028 } 1029 case Fragment.CREATED: 1030 if (newState < Fragment.CREATED) { 1031 if (mDestroyed) { 1032 if (f.mAnimatingAway != null) { 1033 // The fragment's containing activity is 1034 // being destroyed, but this fragment is 1035 // currently animating away. Stop the 1036 // animation right now -- it is not needed, 1037 // and we can't wait any more on destroying 1038 // the fragment. 1039 View v = f.mAnimatingAway; 1040 f.mAnimatingAway = null; 1041 v.clearAnimation(); 1042 } 1043 } 1044 if (f.mAnimatingAway != null) { 1045 // We are waiting for the fragment's view to finish 1046 // animating away. Just make a note of the state 1047 // the fragment now should move to once the animation 1048 // is done. 1049 f.mStateAfterAnimating = newState; 1050 newState = Fragment.CREATED; 1051 } else { 1052 if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f); 1053 if (!f.mRetaining) { 1054 f.performDestroy(); 1055 } 1056 1057 f.mCalled = false; 1058 f.onDetach(); 1059 if (!f.mCalled) { 1060 throw new SuperNotCalledException("Fragment " + f 1061 + " did not call through to super.onDetach()"); 1062 } 1063 if (!keepActive) { 1064 if (!f.mRetaining) { 1065 makeInactive(f); 1066 } else { 1067 f.mActivity = null; 1068 f.mFragmentManager = null; 1069 } 1070 } 1071 } 1072 } 1073 } 1074 } 1075 1076 f.mState = newState; 1077 } 1078 1079 void moveToState(Fragment f) { 1080 moveToState(f, mCurState, 0, 0, false); 1081 } 1082 1083 void moveToState(int newState, boolean always) { 1084 moveToState(newState, 0, 0, always); 1085 } 1086 1087 void moveToState(int newState, int transit, int transitStyle, boolean always) { 1088 if (mActivity == null && newState != Fragment.INITIALIZING) { 1089 throw new IllegalStateException("No activity"); 1090 } 1091 1092 if (!always && mCurState == newState) { 1093 return; 1094 } 1095 1096 mCurState = newState; 1097 if (mActive != null) { 1098 boolean loadersRunning = false; 1099 for (int i=0; i<mActive.size(); i++) { 1100 Fragment f = mActive.get(i); 1101 if (f != null) { 1102 moveToState(f, newState, transit, transitStyle, false); 1103 if (f.mLoaderManager != null) { 1104 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 1105 } 1106 } 1107 } 1108 1109 if (!loadersRunning) { 1110 startPendingDeferredFragments(); 1111 } 1112 1113 if (mNeedMenuInvalidate && mActivity != null && mCurState == Fragment.RESUMED) { 1114 mActivity.supportInvalidateOptionsMenu(); 1115 mNeedMenuInvalidate = false; 1116 } 1117 } 1118 } 1119 1120 void startPendingDeferredFragments() { 1121 if (mActive == null) return; 1122 1123 for (int i=0; i<mActive.size(); i++) { 1124 Fragment f = mActive.get(i); 1125 if (f != null) { 1126 performPendingDeferredStart(f); 1127 } 1128 } 1129 } 1130 1131 void makeActive(Fragment f) { 1132 if (f.mIndex >= 0) { 1133 return; 1134 } 1135 1136 if (mAvailIndices == null || mAvailIndices.size() <= 0) { 1137 if (mActive == null) { 1138 mActive = new ArrayList<Fragment>(); 1139 } 1140 f.setIndex(mActive.size(), mParent); 1141 mActive.add(f); 1142 1143 } else { 1144 f.setIndex(mAvailIndices.remove(mAvailIndices.size()-1), mParent); 1145 mActive.set(f.mIndex, f); 1146 } 1147 if (DEBUG) Log.v(TAG, "Allocated fragment index " + f); 1148 } 1149 1150 void makeInactive(Fragment f) { 1151 if (f.mIndex < 0) { 1152 return; 1153 } 1154 1155 if (DEBUG) Log.v(TAG, "Freeing fragment index " + f); 1156 mActive.set(f.mIndex, null); 1157 if (mAvailIndices == null) { 1158 mAvailIndices = new ArrayList<Integer>(); 1159 } 1160 mAvailIndices.add(f.mIndex); 1161 mActivity.invalidateSupportFragment(f.mWho); 1162 f.initState(); 1163 } 1164 1165 public void addFragment(Fragment fragment, boolean moveToStateNow) { 1166 if (mAdded == null) { 1167 mAdded = new ArrayList<Fragment>(); 1168 } 1169 if (DEBUG) Log.v(TAG, "add: " + fragment); 1170 makeActive(fragment); 1171 if (!fragment.mDetached) { 1172 if (mAdded.contains(fragment)) { 1173 throw new IllegalStateException("Fragment already added: " + fragment); 1174 } 1175 mAdded.add(fragment); 1176 fragment.mAdded = true; 1177 fragment.mRemoving = false; 1178 if (fragment.mHasMenu && fragment.mMenuVisible) { 1179 mNeedMenuInvalidate = true; 1180 } 1181 if (moveToStateNow) { 1182 moveToState(fragment); 1183 } 1184 } 1185 } 1186 1187 public void removeFragment(Fragment fragment, int transition, int transitionStyle) { 1188 if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); 1189 final boolean inactive = !fragment.isInBackStack(); 1190 if (!fragment.mDetached || inactive) { 1191 if (mAdded != null) { 1192 mAdded.remove(fragment); 1193 } 1194 if (fragment.mHasMenu && fragment.mMenuVisible) { 1195 mNeedMenuInvalidate = true; 1196 } 1197 fragment.mAdded = false; 1198 fragment.mRemoving = true; 1199 moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED, 1200 transition, transitionStyle, false); 1201 } 1202 } 1203 1204 public void hideFragment(Fragment fragment, int transition, int transitionStyle) { 1205 if (DEBUG) Log.v(TAG, "hide: " + fragment); 1206 if (!fragment.mHidden) { 1207 fragment.mHidden = true; 1208 if (fragment.mView != null) { 1209 Animation anim = loadAnimation(fragment, transition, true, 1210 transitionStyle); 1211 if (anim != null) { 1212 fragment.mView.startAnimation(anim); 1213 } 1214 fragment.mView.setVisibility(View.GONE); 1215 } 1216 if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) { 1217 mNeedMenuInvalidate = true; 1218 } 1219 fragment.onHiddenChanged(true); 1220 } 1221 } 1222 1223 public void showFragment(Fragment fragment, int transition, int transitionStyle) { 1224 if (DEBUG) Log.v(TAG, "show: " + fragment); 1225 if (fragment.mHidden) { 1226 fragment.mHidden = false; 1227 if (fragment.mView != null) { 1228 Animation anim = loadAnimation(fragment, transition, true, 1229 transitionStyle); 1230 if (anim != null) { 1231 fragment.mView.startAnimation(anim); 1232 } 1233 fragment.mView.setVisibility(View.VISIBLE); 1234 } 1235 if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) { 1236 mNeedMenuInvalidate = true; 1237 } 1238 fragment.onHiddenChanged(false); 1239 } 1240 } 1241 1242 public void detachFragment(Fragment fragment, int transition, int transitionStyle) { 1243 if (DEBUG) Log.v(TAG, "detach: " + fragment); 1244 if (!fragment.mDetached) { 1245 fragment.mDetached = true; 1246 if (fragment.mAdded) { 1247 // We are not already in back stack, so need to remove the fragment. 1248 if (mAdded != null) { 1249 if (DEBUG) Log.v(TAG, "remove from detach: " + fragment); 1250 mAdded.remove(fragment); 1251 } 1252 if (fragment.mHasMenu && fragment.mMenuVisible) { 1253 mNeedMenuInvalidate = true; 1254 } 1255 fragment.mAdded = false; 1256 moveToState(fragment, Fragment.CREATED, transition, transitionStyle, false); 1257 } 1258 } 1259 } 1260 1261 public void attachFragment(Fragment fragment, int transition, int transitionStyle) { 1262 if (DEBUG) Log.v(TAG, "attach: " + fragment); 1263 if (fragment.mDetached) { 1264 fragment.mDetached = false; 1265 if (!fragment.mAdded) { 1266 if (mAdded == null) { 1267 mAdded = new ArrayList<Fragment>(); 1268 } 1269 if (mAdded.contains(fragment)) { 1270 throw new IllegalStateException("Fragment already added: " + fragment); 1271 } 1272 if (DEBUG) Log.v(TAG, "add from attach: " + fragment); 1273 mAdded.add(fragment); 1274 fragment.mAdded = true; 1275 if (fragment.mHasMenu && fragment.mMenuVisible) { 1276 mNeedMenuInvalidate = true; 1277 } 1278 moveToState(fragment, mCurState, transition, transitionStyle, false); 1279 } 1280 } 1281 } 1282 1283 public Fragment findFragmentById(int id) { 1284 if (mAdded != null) { 1285 // First look through added fragments. 1286 for (int i=mAdded.size()-1; i>=0; i--) { 1287 Fragment f = mAdded.get(i); 1288 if (f != null && f.mFragmentId == id) { 1289 return f; 1290 } 1291 } 1292 } 1293 if (mActive != null) { 1294 // Now for any known fragment. 1295 for (int i=mActive.size()-1; i>=0; i--) { 1296 Fragment f = mActive.get(i); 1297 if (f != null && f.mFragmentId == id) { 1298 return f; 1299 } 1300 } 1301 } 1302 return null; 1303 } 1304 1305 public Fragment findFragmentByTag(String tag) { 1306 if (mAdded != null && tag != null) { 1307 // First look through added fragments. 1308 for (int i=mAdded.size()-1; i>=0; i--) { 1309 Fragment f = mAdded.get(i); 1310 if (f != null && tag.equals(f.mTag)) { 1311 return f; 1312 } 1313 } 1314 } 1315 if (mActive != null && tag != null) { 1316 // Now for any known fragment. 1317 for (int i=mActive.size()-1; i>=0; i--) { 1318 Fragment f = mActive.get(i); 1319 if (f != null && tag.equals(f.mTag)) { 1320 return f; 1321 } 1322 } 1323 } 1324 return null; 1325 } 1326 1327 public Fragment findFragmentByWho(String who) { 1328 if (mActive != null && who != null) { 1329 for (int i=mActive.size()-1; i>=0; i--) { 1330 Fragment f = mActive.get(i); 1331 if (f != null && (f=f.findFragmentByWho(who)) != null) { 1332 return f; 1333 } 1334 } 1335 } 1336 return null; 1337 } 1338 1339 private void checkStateLoss() { 1340 if (mStateSaved) { 1341 throw new IllegalStateException( 1342 "Can not perform this action after onSaveInstanceState"); 1343 } 1344 if (mNoTransactionsBecause != null) { 1345 throw new IllegalStateException( 1346 "Can not perform this action inside of " + mNoTransactionsBecause); 1347 } 1348 } 1349 1350 public void enqueueAction(Runnable action, boolean allowStateLoss) { 1351 if (!allowStateLoss) { 1352 checkStateLoss(); 1353 } 1354 synchronized (this) { 1355 if (mActivity == null) { 1356 throw new IllegalStateException("Activity has been destroyed"); 1357 } 1358 if (mPendingActions == null) { 1359 mPendingActions = new ArrayList<Runnable>(); 1360 } 1361 mPendingActions.add(action); 1362 if (mPendingActions.size() == 1) { 1363 mActivity.mHandler.removeCallbacks(mExecCommit); 1364 mActivity.mHandler.post(mExecCommit); 1365 } 1366 } 1367 } 1368 1369 public int allocBackStackIndex(BackStackRecord bse) { 1370 synchronized (this) { 1371 if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) { 1372 if (mBackStackIndices == null) { 1373 mBackStackIndices = new ArrayList<BackStackRecord>(); 1374 } 1375 int index = mBackStackIndices.size(); 1376 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1377 mBackStackIndices.add(bse); 1378 return index; 1379 1380 } else { 1381 int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1); 1382 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1383 mBackStackIndices.set(index, bse); 1384 return index; 1385 } 1386 } 1387 } 1388 1389 public void setBackStackIndex(int index, BackStackRecord bse) { 1390 synchronized (this) { 1391 if (mBackStackIndices == null) { 1392 mBackStackIndices = new ArrayList<BackStackRecord>(); 1393 } 1394 int N = mBackStackIndices.size(); 1395 if (index < N) { 1396 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1397 mBackStackIndices.set(index, bse); 1398 } else { 1399 while (N < index) { 1400 mBackStackIndices.add(null); 1401 if (mAvailBackStackIndices == null) { 1402 mAvailBackStackIndices = new ArrayList<Integer>(); 1403 } 1404 if (DEBUG) Log.v(TAG, "Adding available back stack index " + N); 1405 mAvailBackStackIndices.add(N); 1406 N++; 1407 } 1408 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1409 mBackStackIndices.add(bse); 1410 } 1411 } 1412 } 1413 1414 public void freeBackStackIndex(int index) { 1415 synchronized (this) { 1416 mBackStackIndices.set(index, null); 1417 if (mAvailBackStackIndices == null) { 1418 mAvailBackStackIndices = new ArrayList<Integer>(); 1419 } 1420 if (DEBUG) Log.v(TAG, "Freeing back stack index " + index); 1421 mAvailBackStackIndices.add(index); 1422 } 1423 } 1424 1425 /** 1426 * Only call from main thread! 1427 */ 1428 public boolean execPendingActions() { 1429 if (mExecutingActions) { 1430 throw new IllegalStateException("Recursive entry to executePendingTransactions"); 1431 } 1432 1433 if (Looper.myLooper() != mActivity.mHandler.getLooper()) { 1434 throw new IllegalStateException("Must be called from main thread of process"); 1435 } 1436 1437 boolean didSomething = false; 1438 1439 while (true) { 1440 int numActions; 1441 1442 synchronized (this) { 1443 if (mPendingActions == null || mPendingActions.size() == 0) { 1444 break; 1445 } 1446 1447 numActions = mPendingActions.size(); 1448 if (mTmpActions == null || mTmpActions.length < numActions) { 1449 mTmpActions = new Runnable[numActions]; 1450 } 1451 mPendingActions.toArray(mTmpActions); 1452 mPendingActions.clear(); 1453 mActivity.mHandler.removeCallbacks(mExecCommit); 1454 } 1455 1456 mExecutingActions = true; 1457 for (int i=0; i<numActions; i++) { 1458 mTmpActions[i].run(); 1459 mTmpActions[i] = null; 1460 } 1461 mExecutingActions = false; 1462 didSomething = true; 1463 } 1464 1465 if (mHavePendingDeferredStart) { 1466 boolean loadersRunning = false; 1467 for (int i=0; i<mActive.size(); i++) { 1468 Fragment f = mActive.get(i); 1469 if (f != null && f.mLoaderManager != null) { 1470 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 1471 } 1472 } 1473 if (!loadersRunning) { 1474 mHavePendingDeferredStart = false; 1475 startPendingDeferredFragments(); 1476 } 1477 } 1478 return didSomething; 1479 } 1480 1481 void reportBackStackChanged() { 1482 if (mBackStackChangeListeners != null) { 1483 for (int i=0; i<mBackStackChangeListeners.size(); i++) { 1484 mBackStackChangeListeners.get(i).onBackStackChanged(); 1485 } 1486 } 1487 } 1488 1489 void addBackStackState(BackStackRecord state) { 1490 if (mBackStack == null) { 1491 mBackStack = new ArrayList<BackStackRecord>(); 1492 } 1493 mBackStack.add(state); 1494 reportBackStackChanged(); 1495 } 1496 1497 boolean popBackStackState(Handler handler, String name, int id, int flags) { 1498 if (mBackStack == null) { 1499 return false; 1500 } 1501 if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) { 1502 int last = mBackStack.size()-1; 1503 if (last < 0) { 1504 return false; 1505 } 1506 final BackStackRecord bss = mBackStack.remove(last); 1507 bss.popFromBackStack(true); 1508 reportBackStackChanged(); 1509 } else { 1510 int index = -1; 1511 if (name != null || id >= 0) { 1512 // If a name or ID is specified, look for that place in 1513 // the stack. 1514 index = mBackStack.size()-1; 1515 while (index >= 0) { 1516 BackStackRecord bss = mBackStack.get(index); 1517 if (name != null && name.equals(bss.getName())) { 1518 break; 1519 } 1520 if (id >= 0 && id == bss.mIndex) { 1521 break; 1522 } 1523 index--; 1524 } 1525 if (index < 0) { 1526 return false; 1527 } 1528 if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) { 1529 index--; 1530 // Consume all following entries that match. 1531 while (index >= 0) { 1532 BackStackRecord bss = mBackStack.get(index); 1533 if ((name != null && name.equals(bss.getName())) 1534 || (id >= 0 && id == bss.mIndex)) { 1535 index--; 1536 continue; 1537 } 1538 break; 1539 } 1540 } 1541 } 1542 if (index == mBackStack.size()-1) { 1543 return false; 1544 } 1545 final ArrayList<BackStackRecord> states 1546 = new ArrayList<BackStackRecord>(); 1547 for (int i=mBackStack.size()-1; i>index; i--) { 1548 states.add(mBackStack.remove(i)); 1549 } 1550 final int LAST = states.size()-1; 1551 for (int i=0; i<=LAST; i++) { 1552 if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i)); 1553 states.get(i).popFromBackStack(i == LAST); 1554 } 1555 reportBackStackChanged(); 1556 } 1557 return true; 1558 } 1559 1560 ArrayList<Fragment> retainNonConfig() { 1561 ArrayList<Fragment> fragments = null; 1562 if (mActive != null) { 1563 for (int i=0; i<mActive.size(); i++) { 1564 Fragment f = mActive.get(i); 1565 if (f != null && f.mRetainInstance) { 1566 if (fragments == null) { 1567 fragments = new ArrayList<Fragment>(); 1568 } 1569 fragments.add(f); 1570 f.mRetaining = true; 1571 f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1; 1572 if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f); 1573 } 1574 } 1575 } 1576 return fragments; 1577 } 1578 1579 void saveFragmentViewState(Fragment f) { 1580 if (f.mInnerView == null) { 1581 return; 1582 } 1583 if (mStateArray == null) { 1584 mStateArray = new SparseArray<Parcelable>(); 1585 } else { 1586 mStateArray.clear(); 1587 } 1588 f.mInnerView.saveHierarchyState(mStateArray); 1589 if (mStateArray.size() > 0) { 1590 f.mSavedViewState = mStateArray; 1591 mStateArray = null; 1592 } 1593 } 1594 1595 Bundle saveFragmentBasicState(Fragment f) { 1596 Bundle result = null; 1597 1598 if (mStateBundle == null) { 1599 mStateBundle = new Bundle(); 1600 } 1601 f.performSaveInstanceState(mStateBundle); 1602 if (!mStateBundle.isEmpty()) { 1603 result = mStateBundle; 1604 mStateBundle = null; 1605 } 1606 1607 if (f.mView != null) { 1608 saveFragmentViewState(f); 1609 } 1610 if (f.mSavedViewState != null) { 1611 if (result == null) { 1612 result = new Bundle(); 1613 } 1614 result.putSparseParcelableArray( 1615 FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState); 1616 } 1617 if (!f.mUserVisibleHint) { 1618 if (result == null) { 1619 result = new Bundle(); 1620 } 1621 // Only add this if it's not the default value 1622 result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint); 1623 } 1624 1625 return result; 1626 } 1627 1628 Parcelable saveAllState() { 1629 // Make sure all pending operations have now been executed to get 1630 // our state update-to-date. 1631 execPendingActions(); 1632 1633 if (HONEYCOMB) { 1634 // As of Honeycomb, we save state after pausing. Prior to that 1635 // it is before pausing. With fragments this is an issue, since 1636 // there are many things you may do after pausing but before 1637 // stopping that change the fragment state. For those older 1638 // devices, we will not at this point say that we have saved 1639 // the state, so we will allow them to continue doing fragment 1640 // transactions. This retains the same semantics as Honeycomb, 1641 // though you do have the risk of losing the very most recent state 1642 // if the process is killed... we'll live with that. 1643 mStateSaved = true; 1644 } 1645 1646 if (mActive == null || mActive.size() <= 0) { 1647 return null; 1648 } 1649 1650 // First collect all active fragments. 1651 int N = mActive.size(); 1652 FragmentState[] active = new FragmentState[N]; 1653 boolean haveFragments = false; 1654 for (int i=0; i<N; i++) { 1655 Fragment f = mActive.get(i); 1656 if (f != null) { 1657 if (f.mIndex < 0) { 1658 throwException(new IllegalStateException( 1659 "Failure saving state: active " + f 1660 + " has cleared index: " + f.mIndex)); 1661 } 1662 1663 haveFragments = true; 1664 1665 FragmentState fs = new FragmentState(f); 1666 active[i] = fs; 1667 1668 if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) { 1669 fs.mSavedFragmentState = saveFragmentBasicState(f); 1670 1671 if (f.mTarget != null) { 1672 if (f.mTarget.mIndex < 0) { 1673 throwException(new IllegalStateException( 1674 "Failure saving state: " + f 1675 + " has target not in fragment manager: " + f.mTarget)); 1676 } 1677 if (fs.mSavedFragmentState == null) { 1678 fs.mSavedFragmentState = new Bundle(); 1679 } 1680 putFragment(fs.mSavedFragmentState, 1681 FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget); 1682 if (f.mTargetRequestCode != 0) { 1683 fs.mSavedFragmentState.putInt( 1684 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 1685 f.mTargetRequestCode); 1686 } 1687 } 1688 1689 } else { 1690 fs.mSavedFragmentState = f.mSavedFragmentState; 1691 } 1692 1693 if (DEBUG) Log.v(TAG, "Saved state of " + f + ": " 1694 + fs.mSavedFragmentState); 1695 } 1696 } 1697 1698 if (!haveFragments) { 1699 if (DEBUG) Log.v(TAG, "saveAllState: no fragments!"); 1700 return null; 1701 } 1702 1703 int[] added = null; 1704 BackStackState[] backStack = null; 1705 1706 // Build list of currently added fragments. 1707 if (mAdded != null) { 1708 N = mAdded.size(); 1709 if (N > 0) { 1710 added = new int[N]; 1711 for (int i=0; i<N; i++) { 1712 added[i] = mAdded.get(i).mIndex; 1713 if (added[i] < 0) { 1714 throwException(new IllegalStateException( 1715 "Failure saving state: active " + mAdded.get(i) 1716 + " has cleared index: " + added[i])); 1717 } 1718 if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i 1719 + ": " + mAdded.get(i)); 1720 } 1721 } 1722 } 1723 1724 // Now save back stack. 1725 if (mBackStack != null) { 1726 N = mBackStack.size(); 1727 if (N > 0) { 1728 backStack = new BackStackState[N]; 1729 for (int i=0; i<N; i++) { 1730 backStack[i] = new BackStackState(this, mBackStack.get(i)); 1731 if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i 1732 + ": " + mBackStack.get(i)); 1733 } 1734 } 1735 } 1736 1737 FragmentManagerState fms = new FragmentManagerState(); 1738 fms.mActive = active; 1739 fms.mAdded = added; 1740 fms.mBackStack = backStack; 1741 return fms; 1742 } 1743 1744 void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) { 1745 // If there is no saved state at all, then there can not be 1746 // any nonConfig fragments either, so that is that. 1747 if (state == null) return; 1748 FragmentManagerState fms = (FragmentManagerState)state; 1749 if (fms.mActive == null) return; 1750 1751 // First re-attach any non-config instances we are retaining back 1752 // to their saved state, so we don't try to instantiate them again. 1753 if (nonConfig != null) { 1754 for (int i=0; i<nonConfig.size(); i++) { 1755 Fragment f = nonConfig.get(i); 1756 if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f); 1757 FragmentState fs = fms.mActive[f.mIndex]; 1758 fs.mInstance = f; 1759 f.mSavedViewState = null; 1760 f.mBackStackNesting = 0; 1761 f.mInLayout = false; 1762 f.mAdded = false; 1763 f.mTarget = null; 1764 if (fs.mSavedFragmentState != null) { 1765 fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader()); 1766 f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray( 1767 FragmentManagerImpl.VIEW_STATE_TAG); 1768 } 1769 } 1770 } 1771 1772 // Build the full list of active fragments, instantiating them from 1773 // their saved state. 1774 mActive = new ArrayList<Fragment>(fms.mActive.length); 1775 if (mAvailIndices != null) { 1776 mAvailIndices.clear(); 1777 } 1778 for (int i=0; i<fms.mActive.length; i++) { 1779 FragmentState fs = fms.mActive[i]; 1780 if (fs != null) { 1781 Fragment f = fs.instantiate(mActivity, mParent); 1782 if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f); 1783 mActive.add(f); 1784 // Now that the fragment is instantiated (or came from being 1785 // retained above), clear mInstance in case we end up re-restoring 1786 // from this FragmentState again. 1787 fs.mInstance = null; 1788 } else { 1789 mActive.add(null); 1790 if (mAvailIndices == null) { 1791 mAvailIndices = new ArrayList<Integer>(); 1792 } 1793 if (DEBUG) Log.v(TAG, "restoreAllState: avail #" + i); 1794 mAvailIndices.add(i); 1795 } 1796 } 1797 1798 // Update the target of all retained fragments. 1799 if (nonConfig != null) { 1800 for (int i=0; i<nonConfig.size(); i++) { 1801 Fragment f = nonConfig.get(i); 1802 if (f.mTargetIndex >= 0) { 1803 if (f.mTargetIndex < mActive.size()) { 1804 f.mTarget = mActive.get(f.mTargetIndex); 1805 } else { 1806 Log.w(TAG, "Re-attaching retained fragment " + f 1807 + " target no longer exists: " + f.mTargetIndex); 1808 f.mTarget = null; 1809 } 1810 } 1811 } 1812 } 1813 1814 // Build the list of currently added fragments. 1815 if (fms.mAdded != null) { 1816 mAdded = new ArrayList<Fragment>(fms.mAdded.length); 1817 for (int i=0; i<fms.mAdded.length; i++) { 1818 Fragment f = mActive.get(fms.mAdded[i]); 1819 if (f == null) { 1820 throwException(new IllegalStateException( 1821 "No instantiated fragment for index #" + fms.mAdded[i])); 1822 } 1823 f.mAdded = true; 1824 if (DEBUG) Log.v(TAG, "restoreAllState: added #" + i + ": " + f); 1825 if (mAdded.contains(f)) { 1826 throw new IllegalStateException("Already added!"); 1827 } 1828 mAdded.add(f); 1829 } 1830 } else { 1831 mAdded = null; 1832 } 1833 1834 // Build the back stack. 1835 if (fms.mBackStack != null) { 1836 mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length); 1837 for (int i=0; i<fms.mBackStack.length; i++) { 1838 BackStackRecord bse = fms.mBackStack[i].instantiate(this); 1839 if (DEBUG) { 1840 Log.v(TAG, "restoreAllState: back stack #" + i 1841 + " (index " + bse.mIndex + "): " + bse); 1842 LogWriter logw = new LogWriter(TAG); 1843 PrintWriter pw = new PrintWriter(logw); 1844 bse.dump(" ", pw, false); 1845 } 1846 mBackStack.add(bse); 1847 if (bse.mIndex >= 0) { 1848 setBackStackIndex(bse.mIndex, bse); 1849 } 1850 } 1851 } else { 1852 mBackStack = null; 1853 } 1854 } 1855 1856 public void attachActivity(FragmentActivity activity, 1857 FragmentContainer container, Fragment parent) { 1858 if (mActivity != null) throw new IllegalStateException("Already attached"); 1859 mActivity = activity; 1860 mContainer = container; 1861 mParent = parent; 1862 } 1863 1864 public void noteStateNotSaved() { 1865 mStateSaved = false; 1866 } 1867 1868 public void dispatchCreate() { 1869 mStateSaved = false; 1870 moveToState(Fragment.CREATED, false); 1871 } 1872 1873 public void dispatchActivityCreated() { 1874 mStateSaved = false; 1875 moveToState(Fragment.ACTIVITY_CREATED, false); 1876 } 1877 1878 public void dispatchStart() { 1879 mStateSaved = false; 1880 moveToState(Fragment.STARTED, false); 1881 } 1882 1883 public void dispatchResume() { 1884 mStateSaved = false; 1885 moveToState(Fragment.RESUMED, false); 1886 } 1887 1888 public void dispatchPause() { 1889 moveToState(Fragment.STARTED, false); 1890 } 1891 1892 public void dispatchStop() { 1893 // See saveAllState() for the explanation of this. We do this for 1894 // all platform versions, to keep our behavior more consistent between 1895 // them. 1896 mStateSaved = true; 1897 1898 moveToState(Fragment.STOPPED, false); 1899 } 1900 1901 public void dispatchReallyStop() { 1902 moveToState(Fragment.ACTIVITY_CREATED, false); 1903 } 1904 1905 public void dispatchDestroyView() { 1906 moveToState(Fragment.CREATED, false); 1907 } 1908 1909 public void dispatchDestroy() { 1910 mDestroyed = true; 1911 execPendingActions(); 1912 moveToState(Fragment.INITIALIZING, false); 1913 mActivity = null; 1914 mContainer = null; 1915 mParent = null; 1916 } 1917 1918 public void dispatchConfigurationChanged(Configuration newConfig) { 1919 if (mAdded != null) { 1920 for (int i=0; i<mAdded.size(); i++) { 1921 Fragment f = mAdded.get(i); 1922 if (f != null) { 1923 f.performConfigurationChanged(newConfig); 1924 } 1925 } 1926 } 1927 } 1928 1929 public void dispatchLowMemory() { 1930 if (mAdded != null) { 1931 for (int i=0; i<mAdded.size(); i++) { 1932 Fragment f = mAdded.get(i); 1933 if (f != null) { 1934 f.performLowMemory(); 1935 } 1936 } 1937 } 1938 } 1939 1940 public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) { 1941 boolean show = false; 1942 ArrayList<Fragment> newMenus = null; 1943 if (mAdded != null) { 1944 for (int i=0; i<mAdded.size(); i++) { 1945 Fragment f = mAdded.get(i); 1946 if (f != null) { 1947 if (f.performCreateOptionsMenu(menu, inflater)) { 1948 show = true; 1949 if (newMenus == null) { 1950 newMenus = new ArrayList<Fragment>(); 1951 } 1952 newMenus.add(f); 1953 } 1954 } 1955 } 1956 } 1957 1958 if (mCreatedMenus != null) { 1959 for (int i=0; i<mCreatedMenus.size(); i++) { 1960 Fragment f = mCreatedMenus.get(i); 1961 if (newMenus == null || !newMenus.contains(f)) { 1962 f.onDestroyOptionsMenu(); 1963 } 1964 } 1965 } 1966 1967 mCreatedMenus = newMenus; 1968 1969 return show; 1970 } 1971 1972 public boolean dispatchPrepareOptionsMenu(Menu menu) { 1973 boolean show = false; 1974 if (mAdded != null) { 1975 for (int i=0; i<mAdded.size(); i++) { 1976 Fragment f = mAdded.get(i); 1977 if (f != null) { 1978 if (f.performPrepareOptionsMenu(menu)) { 1979 show = true; 1980 } 1981 } 1982 } 1983 } 1984 return show; 1985 } 1986 1987 public boolean dispatchOptionsItemSelected(MenuItem item) { 1988 if (mAdded != null) { 1989 for (int i=0; i<mAdded.size(); i++) { 1990 Fragment f = mAdded.get(i); 1991 if (f != null) { 1992 if (f.performOptionsItemSelected(item)) { 1993 return true; 1994 } 1995 } 1996 } 1997 } 1998 return false; 1999 } 2000 2001 public boolean dispatchContextItemSelected(MenuItem item) { 2002 if (mAdded != null) { 2003 for (int i=0; i<mAdded.size(); i++) { 2004 Fragment f = mAdded.get(i); 2005 if (f != null) { 2006 if (f.performContextItemSelected(item)) { 2007 return true; 2008 } 2009 } 2010 } 2011 } 2012 return false; 2013 } 2014 2015 public void dispatchOptionsMenuClosed(Menu menu) { 2016 if (mAdded != null) { 2017 for (int i=0; i<mAdded.size(); i++) { 2018 Fragment f = mAdded.get(i); 2019 if (f != null) { 2020 f.performOptionsMenuClosed(menu); 2021 } 2022 } 2023 } 2024 } 2025 2026 public static int reverseTransit(int transit) { 2027 int rev = 0; 2028 switch (transit) { 2029 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 2030 rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; 2031 break; 2032 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 2033 rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN; 2034 break; 2035 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 2036 rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE; 2037 break; 2038 } 2039 return rev; 2040 2041 } 2042 2043 public static final int ANIM_STYLE_OPEN_ENTER = 1; 2044 public static final int ANIM_STYLE_OPEN_EXIT = 2; 2045 public static final int ANIM_STYLE_CLOSE_ENTER = 3; 2046 public static final int ANIM_STYLE_CLOSE_EXIT = 4; 2047 public static final int ANIM_STYLE_FADE_ENTER = 5; 2048 public static final int ANIM_STYLE_FADE_EXIT = 6; 2049 2050 public static int transitToStyleIndex(int transit, boolean enter) { 2051 int animAttr = -1; 2052 switch (transit) { 2053 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 2054 animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT; 2055 break; 2056 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 2057 animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT; 2058 break; 2059 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 2060 animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT; 2061 break; 2062 } 2063 return animAttr; 2064 } 2065} 2066