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