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