FragmentManager.java revision 9c53b844bd525e6a04e17291efc38713893074cd
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 757 if (f.mState < newState) { 758 // For fragments that are created from a layout, when restoring from 759 // state we don't want to allow them to be created until they are 760 // being reloaded from the layout. 761 if (f.mFromLayout && !f.mInLayout) { 762 return; 763 } 764 if (f.mAnimatingAway != null) { 765 // The fragment is currently being animated... but! Now we 766 // want to move our state back up. Give up on waiting for the 767 // animation, move to whatever the final state should be once 768 // the animation is done, and then we can proceed from there. 769 f.mAnimatingAway = null; 770 moveToState(f, f.mStateAfterAnimating, 0, 0); 771 } 772 switch (f.mState) { 773 case Fragment.INITIALIZING: 774 if (DEBUG) Log.v(TAG, "moveto CREATED: " + f); 775 if (f.mSavedFragmentState != null) { 776 f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray( 777 FragmentManagerImpl.VIEW_STATE_TAG); 778 f.mTarget = getFragment(f.mSavedFragmentState, 779 FragmentManagerImpl.TARGET_STATE_TAG); 780 if (f.mTarget != null) { 781 f.mTargetRequestCode = f.mSavedFragmentState.getInt( 782 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0); 783 } 784 } 785 f.mActivity = mActivity; 786 f.mFragmentManager = mActivity.mFragments; 787 f.mCalled = false; 788 f.onAttach(mActivity); 789 if (!f.mCalled) { 790 throw new SuperNotCalledException("Fragment " + f 791 + " did not call through to super.onAttach()"); 792 } 793 mActivity.onAttachFragment(f); 794 795 if (!f.mRetaining) { 796 f.mCalled = false; 797 f.onCreate(f.mSavedFragmentState); 798 if (!f.mCalled) { 799 throw new SuperNotCalledException("Fragment " + f 800 + " did not call through to super.onCreate()"); 801 } 802 } 803 f.mRetaining = false; 804 if (f.mFromLayout) { 805 // For fragments that are part of the content view 806 // layout, we need to instantiate the view immediately 807 // and the inflater will take care of adding it. 808 f.mView = f.onCreateView(f.getLayoutInflater(f.mSavedFragmentState), 809 null, f.mSavedFragmentState); 810 if (f.mView != null) { 811 f.mInnerView = f.mView; 812 f.mView = NoSaveStateFrameLayout.wrap(f.mView); 813 if (f.mHidden) f.mView.setVisibility(View.GONE); 814 f.onViewCreated(f.mView, f.mSavedFragmentState); 815 } else { 816 f.mInnerView = null; 817 } 818 } 819 case Fragment.CREATED: 820 if (newState > Fragment.CREATED) { 821 if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f); 822 if (!f.mFromLayout) { 823 ViewGroup container = null; 824 if (f.mContainerId != 0) { 825 container = (ViewGroup)mActivity.findViewById(f.mContainerId); 826 if (container == null && !f.mRestored) { 827 throw new IllegalArgumentException("No view found for id 0x" 828 + Integer.toHexString(f.mContainerId) 829 + " for fragment " + f); 830 } 831 } 832 f.mContainer = container; 833 f.mView = f.onCreateView(f.getLayoutInflater(f.mSavedFragmentState), 834 container, f.mSavedFragmentState); 835 if (f.mView != null) { 836 f.mInnerView = f.mView; 837 f.mView = NoSaveStateFrameLayout.wrap(f.mView); 838 if (container != null) { 839 Animation anim = loadAnimation(f, transit, true, 840 transitionStyle); 841 if (anim != null) { 842 f.mView.startAnimation(anim); 843 } 844 container.addView(f.mView); 845 } 846 if (f.mHidden) f.mView.setVisibility(View.GONE); 847 f.onViewCreated(f.mView, f.mSavedFragmentState); 848 } else { 849 f.mInnerView = null; 850 } 851 } 852 853 f.mCalled = false; 854 f.onActivityCreated(f.mSavedFragmentState); 855 if (!f.mCalled) { 856 throw new SuperNotCalledException("Fragment " + f 857 + " did not call through to super.onActivityCreated()"); 858 } 859 if (f.mView != null) { 860 f.restoreViewState(); 861 } 862 f.mSavedFragmentState = null; 863 } 864 case Fragment.ACTIVITY_CREATED: 865 case Fragment.STOPPED: 866 if (newState > Fragment.STOPPED) { 867 if (DEBUG) Log.v(TAG, "moveto STARTED: " + f); 868 f.mCalled = false; 869 f.performStart(); 870 if (!f.mCalled) { 871 throw new SuperNotCalledException("Fragment " + f 872 + " did not call through to super.onStart()"); 873 } 874 } 875 case Fragment.STARTED: 876 if (newState > Fragment.STARTED) { 877 if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f); 878 f.mCalled = false; 879 f.mResumed = true; 880 f.onResume(); 881 if (!f.mCalled) { 882 throw new SuperNotCalledException("Fragment " + f 883 + " did not call through to super.onResume()"); 884 } 885 } 886 } 887 } else if (f.mState > newState) { 888 switch (f.mState) { 889 case Fragment.RESUMED: 890 if (newState < Fragment.RESUMED) { 891 if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f); 892 f.mCalled = false; 893 f.onPause(); 894 if (!f.mCalled) { 895 throw new SuperNotCalledException("Fragment " + f 896 + " did not call through to super.onPause()"); 897 } 898 f.mResumed = false; 899 } 900 case Fragment.STARTED: 901 if (newState < Fragment.STARTED) { 902 if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f); 903 f.mCalled = false; 904 f.performStop(); 905 if (!f.mCalled) { 906 throw new SuperNotCalledException("Fragment " + f 907 + " did not call through to super.onStop()"); 908 } 909 } 910 case Fragment.STOPPED: 911 case Fragment.ACTIVITY_CREATED: 912 if (newState < Fragment.ACTIVITY_CREATED) { 913 if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f); 914 if (f.mView != null) { 915 // Need to save the current view state if not 916 // done already. 917 if (!mActivity.isFinishing() && f.mSavedViewState == null) { 918 saveFragmentViewState(f); 919 } 920 } 921 f.mCalled = false; 922 f.performDestroyView(); 923 if (!f.mCalled) { 924 throw new SuperNotCalledException("Fragment " + f 925 + " did not call through to super.onDestroyView()"); 926 } 927 if (f.mView != null && f.mContainer != null) { 928 Animation anim = null; 929 if (mCurState > Fragment.INITIALIZING && !mDestroyed) { 930 anim = loadAnimation(f, transit, false, 931 transitionStyle); 932 } 933 if (anim != null) { 934 final Fragment fragment = f; 935 f.mAnimatingAway = f.mView; 936 f.mStateAfterAnimating = newState; 937 anim.setAnimationListener(new AnimationListener() { 938 @Override 939 public void onAnimationEnd(Animation animation) { 940 if (fragment.mAnimatingAway != null) { 941 fragment.mAnimatingAway = null; 942 moveToState(fragment, fragment.mStateAfterAnimating, 943 0, 0); 944 } 945 } 946 @Override 947 public void onAnimationRepeat(Animation animation) { 948 } 949 @Override 950 public void onAnimationStart(Animation animation) { 951 } 952 }); 953 f.mView.startAnimation(anim); 954 } 955 f.mContainer.removeView(f.mView); 956 } 957 f.mContainer = null; 958 f.mView = null; 959 f.mInnerView = null; 960 } 961 case Fragment.CREATED: 962 if (newState < Fragment.CREATED) { 963 if (mDestroyed) { 964 if (f.mAnimatingAway != null) { 965 // The fragment's containing activity is 966 // being destroyed, but this fragment is 967 // currently animating away. Stop the 968 // animation right now -- it is not needed, 969 // and we can't wait any more on destroying 970 // the fragment. 971 View v = f.mAnimatingAway; 972 f.mAnimatingAway = null; 973 v.clearAnimation(); 974 } 975 } 976 if (f.mAnimatingAway != null) { 977 // We are waiting for the fragment's view to finish 978 // animating away. Just make a note of the state 979 // the fragment now should move to once the animation 980 // is done. 981 f.mStateAfterAnimating = newState; 982 } else { 983 if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f); 984 if (!f.mRetaining) { 985 f.mCalled = false; 986 f.onDestroy(); 987 if (!f.mCalled) { 988 throw new SuperNotCalledException("Fragment " + f 989 + " did not call through to super.onDestroy()"); 990 } 991 } 992 993 f.mCalled = false; 994 f.onDetach(); 995 if (!f.mCalled) { 996 throw new SuperNotCalledException("Fragment " + f 997 + " did not call through to super.onDetach()"); 998 } 999 f.mImmediateActivity = null; 1000 f.mActivity = null; 1001 f.mFragmentManager = null; 1002 } 1003 } 1004 } 1005 } 1006 1007 f.mState = newState; 1008 } 1009 1010 void moveToState(Fragment f) { 1011 moveToState(f, mCurState, 0, 0); 1012 } 1013 1014 void moveToState(int newState, boolean always) { 1015 moveToState(newState, 0, 0, always); 1016 } 1017 1018 void moveToState(int newState, int transit, int transitStyle, boolean always) { 1019 if (mActivity == null && newState != Fragment.INITIALIZING) { 1020 throw new IllegalStateException("No activity"); 1021 } 1022 1023 if (!always && mCurState == newState) { 1024 return; 1025 } 1026 1027 mCurState = newState; 1028 if (mActive != null) { 1029 for (int i=0; i<mActive.size(); i++) { 1030 Fragment f = mActive.get(i); 1031 if (f != null) { 1032 moveToState(f, newState, transit, transitStyle); 1033 } 1034 } 1035 1036 if (mNeedMenuInvalidate && mActivity != null) { 1037 mActivity.supportInvalidateOptionsMenu(); 1038 mNeedMenuInvalidate = false; 1039 } 1040 } 1041 } 1042 1043 void makeActive(Fragment f) { 1044 if (f.mIndex >= 0) { 1045 return; 1046 } 1047 1048 if (mAvailIndices == null || mAvailIndices.size() <= 0) { 1049 if (mActive == null) { 1050 mActive = new ArrayList<Fragment>(); 1051 } 1052 f.setIndex(mActive.size()); 1053 mActive.add(f); 1054 1055 } else { 1056 f.setIndex(mAvailIndices.remove(mAvailIndices.size()-1)); 1057 mActive.set(f.mIndex, f); 1058 } 1059 } 1060 1061 void makeInactive(Fragment f) { 1062 if (f.mIndex < 0) { 1063 return; 1064 } 1065 1066 if (DEBUG) Log.v(TAG, "Freeing fragment index " + f.mIndex); 1067 mActive.set(f.mIndex, null); 1068 if (mAvailIndices == null) { 1069 mAvailIndices = new ArrayList<Integer>(); 1070 } 1071 mAvailIndices.add(f.mIndex); 1072 mActivity.invalidateSupportFragmentIndex(f.mIndex); 1073 f.initState(); 1074 } 1075 1076 public void addFragment(Fragment fragment, boolean moveToStateNow) { 1077 if (mAdded == null) { 1078 mAdded = new ArrayList<Fragment>(); 1079 } 1080 if (DEBUG) Log.v(TAG, "add: " + fragment); 1081 makeActive(fragment); 1082 if (!fragment.mDetached) { 1083 mAdded.add(fragment); 1084 fragment.mAdded = true; 1085 fragment.mRemoving = false; 1086 if (fragment.mHasMenu) { 1087 mNeedMenuInvalidate = true; 1088 } 1089 if (moveToStateNow) { 1090 moveToState(fragment); 1091 } 1092 } 1093 } 1094 1095 public void removeFragment(Fragment fragment, int transition, int transitionStyle) { 1096 if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); 1097 final boolean inactive = !fragment.isInBackStack(); 1098 if (!fragment.mDetached || inactive) { 1099 mAdded.remove(fragment); 1100 if (fragment.mHasMenu) { 1101 mNeedMenuInvalidate = true; 1102 } 1103 fragment.mAdded = false; 1104 fragment.mRemoving = true; 1105 moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED, 1106 transition, transitionStyle); 1107 if (inactive) { 1108 makeInactive(fragment); 1109 } 1110 } 1111 } 1112 1113 public void hideFragment(Fragment fragment, int transition, int transitionStyle) { 1114 if (DEBUG) Log.v(TAG, "hide: " + fragment); 1115 if (!fragment.mHidden) { 1116 fragment.mHidden = true; 1117 if (fragment.mView != null) { 1118 Animation anim = loadAnimation(fragment, transition, true, 1119 transitionStyle); 1120 if (anim != null) { 1121 fragment.mView.startAnimation(anim); 1122 } 1123 fragment.mView.setVisibility(View.GONE); 1124 } 1125 if (fragment.mAdded && fragment.mHasMenu) { 1126 mNeedMenuInvalidate = true; 1127 } 1128 fragment.onHiddenChanged(true); 1129 } 1130 } 1131 1132 public void showFragment(Fragment fragment, int transition, int transitionStyle) { 1133 if (DEBUG) Log.v(TAG, "show: " + fragment); 1134 if (fragment.mHidden) { 1135 fragment.mHidden = false; 1136 if (fragment.mView != null) { 1137 Animation anim = loadAnimation(fragment, transition, true, 1138 transitionStyle); 1139 if (anim != null) { 1140 fragment.mView.startAnimation(anim); 1141 } 1142 fragment.mView.setVisibility(View.VISIBLE); 1143 } 1144 if (fragment.mAdded && fragment.mHasMenu) { 1145 mNeedMenuInvalidate = true; 1146 } 1147 fragment.onHiddenChanged(false); 1148 } 1149 } 1150 1151 public void detachFragment(Fragment fragment, int transition, int transitionStyle) { 1152 if (DEBUG) Log.v(TAG, "detach: " + fragment); 1153 if (!fragment.mDetached) { 1154 fragment.mDetached = true; 1155 if (fragment.mAdded) { 1156 // We are not already in back stack, so need to remove the fragment. 1157 mAdded.remove(fragment); 1158 if (fragment.mHasMenu) { 1159 mNeedMenuInvalidate = true; 1160 } 1161 fragment.mAdded = false; 1162 moveToState(fragment, Fragment.CREATED, transition, transitionStyle); 1163 } 1164 } 1165 } 1166 1167 public void attachFragment(Fragment fragment, int transition, int transitionStyle) { 1168 if (DEBUG) Log.v(TAG, "attach: " + fragment); 1169 if (fragment.mDetached) { 1170 fragment.mDetached = false; 1171 if (!fragment.mAdded) { 1172 mAdded.add(fragment); 1173 fragment.mAdded = true; 1174 if (fragment.mHasMenu) { 1175 mNeedMenuInvalidate = true; 1176 } 1177 moveToState(fragment, mCurState, transition, transitionStyle); 1178 } 1179 } 1180 } 1181 1182 public Fragment findFragmentById(int id) { 1183 if (mActive != null) { 1184 // First look through added fragments. 1185 for (int i=mAdded.size()-1; i>=0; i--) { 1186 Fragment f = mAdded.get(i); 1187 if (f != null && f.mFragmentId == id) { 1188 return f; 1189 } 1190 } 1191 // Now for any known fragment. 1192 for (int i=mActive.size()-1; i>=0; i--) { 1193 Fragment f = mActive.get(i); 1194 if (f != null && f.mFragmentId == id) { 1195 return f; 1196 } 1197 } 1198 } 1199 return null; 1200 } 1201 1202 public Fragment findFragmentByTag(String tag) { 1203 if (mActive != null && tag != null) { 1204 // First look through added fragments. 1205 for (int i=mAdded.size()-1; i>=0; i--) { 1206 Fragment f = mAdded.get(i); 1207 if (f != null && tag.equals(f.mTag)) { 1208 return f; 1209 } 1210 } 1211 // Now for any known fragment. 1212 for (int i=mActive.size()-1; i>=0; i--) { 1213 Fragment f = mActive.get(i); 1214 if (f != null && tag.equals(f.mTag)) { 1215 return f; 1216 } 1217 } 1218 } 1219 return null; 1220 } 1221 1222 public Fragment findFragmentByWho(String who) { 1223 if (mActive != null && who != null) { 1224 for (int i=mActive.size()-1; i>=0; i--) { 1225 Fragment f = mActive.get(i); 1226 if (f != null && who.equals(f.mWho)) { 1227 return f; 1228 } 1229 } 1230 } 1231 return null; 1232 } 1233 1234 private void checkStateLoss() { 1235 if (mStateSaved) { 1236 throw new IllegalStateException( 1237 "Can not perform this action after onSaveInstanceState"); 1238 } 1239 if (mNoTransactionsBecause != null) { 1240 throw new IllegalStateException( 1241 "Can not perform this action inside of " + mNoTransactionsBecause); 1242 } 1243 } 1244 1245 public void enqueueAction(Runnable action, boolean allowStateLoss) { 1246 if (!allowStateLoss) { 1247 checkStateLoss(); 1248 } 1249 synchronized (this) { 1250 if (mActivity == null) { 1251 throw new IllegalStateException("Activity has been destroyed"); 1252 } 1253 if (mPendingActions == null) { 1254 mPendingActions = new ArrayList<Runnable>(); 1255 } 1256 mPendingActions.add(action); 1257 if (mPendingActions.size() == 1) { 1258 mActivity.mHandler.removeCallbacks(mExecCommit); 1259 mActivity.mHandler.post(mExecCommit); 1260 } 1261 } 1262 } 1263 1264 public int allocBackStackIndex(BackStackRecord bse) { 1265 synchronized (this) { 1266 if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) { 1267 if (mBackStackIndices == null) { 1268 mBackStackIndices = new ArrayList<BackStackRecord>(); 1269 } 1270 int index = mBackStackIndices.size(); 1271 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1272 mBackStackIndices.add(bse); 1273 return index; 1274 1275 } else { 1276 int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1); 1277 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1278 mBackStackIndices.set(index, bse); 1279 return index; 1280 } 1281 } 1282 } 1283 1284 public void setBackStackIndex(int index, BackStackRecord bse) { 1285 synchronized (this) { 1286 if (mBackStackIndices == null) { 1287 mBackStackIndices = new ArrayList<BackStackRecord>(); 1288 } 1289 int N = mBackStackIndices.size(); 1290 if (index < N) { 1291 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1292 mBackStackIndices.set(index, bse); 1293 } else { 1294 while (N < index) { 1295 mBackStackIndices.add(null); 1296 if (mAvailBackStackIndices == null) { 1297 mAvailBackStackIndices = new ArrayList<Integer>(); 1298 } 1299 if (DEBUG) Log.v(TAG, "Adding available back stack index " + N); 1300 mAvailBackStackIndices.add(N); 1301 N++; 1302 } 1303 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1304 mBackStackIndices.add(bse); 1305 } 1306 } 1307 } 1308 1309 public void freeBackStackIndex(int index) { 1310 synchronized (this) { 1311 mBackStackIndices.set(index, null); 1312 if (mAvailBackStackIndices == null) { 1313 mAvailBackStackIndices = new ArrayList<Integer>(); 1314 } 1315 if (DEBUG) Log.v(TAG, "Freeing back stack index " + index); 1316 mAvailBackStackIndices.add(index); 1317 } 1318 } 1319 1320 /** 1321 * Only call from main thread! 1322 */ 1323 public boolean execPendingActions() { 1324 if (mExecutingActions) { 1325 throw new IllegalStateException("Recursive entry to executePendingTransactions"); 1326 } 1327 1328 if (Looper.myLooper() != mActivity.mHandler.getLooper()) { 1329 throw new IllegalStateException("Must be called from main thread of process"); 1330 } 1331 1332 boolean didSomething = false; 1333 1334 while (true) { 1335 int numActions; 1336 1337 synchronized (this) { 1338 if (mPendingActions == null || mPendingActions.size() == 0) { 1339 return didSomething; 1340 } 1341 1342 numActions = mPendingActions.size(); 1343 if (mTmpActions == null || mTmpActions.length < numActions) { 1344 mTmpActions = new Runnable[numActions]; 1345 } 1346 mPendingActions.toArray(mTmpActions); 1347 mPendingActions.clear(); 1348 mActivity.mHandler.removeCallbacks(mExecCommit); 1349 } 1350 1351 mExecutingActions = true; 1352 for (int i=0; i<numActions; i++) { 1353 mTmpActions[i].run(); 1354 } 1355 mExecutingActions = false; 1356 didSomething = true; 1357 } 1358 } 1359 1360 void reportBackStackChanged() { 1361 if (mBackStackChangeListeners != null) { 1362 for (int i=0; i<mBackStackChangeListeners.size(); i++) { 1363 mBackStackChangeListeners.get(i).onBackStackChanged(); 1364 } 1365 } 1366 } 1367 1368 void addBackStackState(BackStackRecord state) { 1369 if (mBackStack == null) { 1370 mBackStack = new ArrayList<BackStackRecord>(); 1371 } 1372 mBackStack.add(state); 1373 reportBackStackChanged(); 1374 } 1375 1376 boolean popBackStackState(Handler handler, String name, int id, int flags) { 1377 if (mBackStack == null) { 1378 return false; 1379 } 1380 if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) { 1381 int last = mBackStack.size()-1; 1382 if (last < 0) { 1383 return false; 1384 } 1385 final BackStackRecord bss = mBackStack.remove(last); 1386 bss.popFromBackStack(true); 1387 reportBackStackChanged(); 1388 } else { 1389 int index = -1; 1390 if (name != null || id >= 0) { 1391 // If a name or ID is specified, look for that place in 1392 // the stack. 1393 index = mBackStack.size()-1; 1394 while (index >= 0) { 1395 BackStackRecord bss = mBackStack.get(index); 1396 if (name != null && name.equals(bss.getName())) { 1397 break; 1398 } 1399 if (id >= 0 && id == bss.mIndex) { 1400 break; 1401 } 1402 index--; 1403 } 1404 if (index < 0) { 1405 return false; 1406 } 1407 if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) { 1408 index--; 1409 // Consume all following entries that match. 1410 while (index >= 0) { 1411 BackStackRecord bss = mBackStack.get(index); 1412 if ((name != null && name.equals(bss.getName())) 1413 || (id >= 0 && id == bss.mIndex)) { 1414 index--; 1415 continue; 1416 } 1417 break; 1418 } 1419 } 1420 } 1421 if (index == mBackStack.size()-1) { 1422 return false; 1423 } 1424 final ArrayList<BackStackRecord> states 1425 = new ArrayList<BackStackRecord>(); 1426 for (int i=mBackStack.size()-1; i>index; i--) { 1427 states.add(mBackStack.remove(i)); 1428 } 1429 final int LAST = states.size()-1; 1430 for (int i=0; i<=LAST; i++) { 1431 if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i)); 1432 states.get(i).popFromBackStack(i == LAST); 1433 } 1434 reportBackStackChanged(); 1435 } 1436 return true; 1437 } 1438 1439 ArrayList<Fragment> retainNonConfig() { 1440 ArrayList<Fragment> fragments = null; 1441 if (mActive != null) { 1442 for (int i=0; i<mActive.size(); i++) { 1443 Fragment f = mActive.get(i); 1444 if (f != null && f.mRetainInstance) { 1445 if (fragments == null) { 1446 fragments = new ArrayList<Fragment>(); 1447 } 1448 fragments.add(f); 1449 f.mRetaining = true; 1450 } 1451 } 1452 } 1453 return fragments; 1454 } 1455 1456 void saveFragmentViewState(Fragment f) { 1457 if (f.mInnerView == null) { 1458 return; 1459 } 1460 if (mStateArray == null) { 1461 mStateArray = new SparseArray<Parcelable>(); 1462 } else { 1463 mStateArray.clear(); 1464 } 1465 f.mInnerView.saveHierarchyState(mStateArray); 1466 if (mStateArray.size() > 0) { 1467 f.mSavedViewState = mStateArray; 1468 mStateArray = null; 1469 } 1470 } 1471 1472 Bundle saveFragmentBasicState(Fragment f) { 1473 Bundle result = null; 1474 1475 if (mStateBundle == null) { 1476 mStateBundle = new Bundle(); 1477 } 1478 f.onSaveInstanceState(mStateBundle); 1479 if (!mStateBundle.isEmpty()) { 1480 result = mStateBundle; 1481 mStateBundle = null; 1482 } 1483 1484 if (f.mView != null) { 1485 saveFragmentViewState(f); 1486 } 1487 if (f.mSavedViewState != null) { 1488 if (result == null) { 1489 result = new Bundle(); 1490 } 1491 result.putSparseParcelableArray( 1492 FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState); 1493 } 1494 1495 return result; 1496 } 1497 1498 Parcelable saveAllState() { 1499 // Make sure all pending operations have now been executed to get 1500 // our state update-to-date. 1501 execPendingActions(); 1502 1503 if (HONEYCOMB) { 1504 // As of Honeycomb, we save state after pausing. Prior to that 1505 // it is before pausing. With fragments this is an issue, since 1506 // there are many things you may do after pausing but before 1507 // stopping that change the fragment state. For those older 1508 // devices, we will not at this point say that we have saved 1509 // the state, so we will allow them to continue doing fragment 1510 // transactions. This retains the same semantics as Honeycomb, 1511 // though you do have the risk of losing the very most recent state 1512 // if the process is killed... we'll live with that. 1513 mStateSaved = true; 1514 } 1515 1516 if (mActive == null || mActive.size() <= 0) { 1517 return null; 1518 } 1519 1520 // First collect all active fragments. 1521 int N = mActive.size(); 1522 FragmentState[] active = new FragmentState[N]; 1523 boolean haveFragments = false; 1524 for (int i=0; i<N; i++) { 1525 Fragment f = mActive.get(i); 1526 if (f != null) { 1527 haveFragments = true; 1528 1529 FragmentState fs = new FragmentState(f); 1530 active[i] = fs; 1531 1532 if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) { 1533 fs.mSavedFragmentState = saveFragmentBasicState(f); 1534 1535 if (f.mTarget != null) { 1536 if (f.mTarget.mIndex < 0) { 1537 String msg = "Failure saving state: " + f 1538 + " has target not in fragment manager: " + f.mTarget; 1539 Log.e(TAG, msg); 1540 dump(" ", null, new PrintWriter(new LogWriter(TAG)), new String[] { }); 1541 throw new IllegalStateException(msg); 1542 } 1543 if (fs.mSavedFragmentState == null) { 1544 fs.mSavedFragmentState = new Bundle(); 1545 } 1546 putFragment(fs.mSavedFragmentState, 1547 FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget); 1548 if (f.mTargetRequestCode != 0) { 1549 fs.mSavedFragmentState.putInt( 1550 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 1551 f.mTargetRequestCode); 1552 } 1553 } 1554 1555 } else { 1556 fs.mSavedFragmentState = f.mSavedFragmentState; 1557 } 1558 1559 if (DEBUG) Log.v(TAG, "Saved state of " + f + ": " 1560 + fs.mSavedFragmentState); 1561 } 1562 } 1563 1564 if (!haveFragments) { 1565 if (DEBUG) Log.v(TAG, "saveAllState: no fragments!"); 1566 return null; 1567 } 1568 1569 int[] added = null; 1570 BackStackState[] backStack = null; 1571 1572 // Build list of currently added fragments. 1573 if (mAdded != null) { 1574 N = mAdded.size(); 1575 if (N > 0) { 1576 added = new int[N]; 1577 for (int i=0; i<N; i++) { 1578 added[i] = mAdded.get(i).mIndex; 1579 if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i 1580 + ": " + mAdded.get(i)); 1581 } 1582 } 1583 } 1584 1585 // Now save back stack. 1586 if (mBackStack != null) { 1587 N = mBackStack.size(); 1588 if (N > 0) { 1589 backStack = new BackStackState[N]; 1590 for (int i=0; i<N; i++) { 1591 backStack[i] = new BackStackState(this, mBackStack.get(i)); 1592 if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i 1593 + ": " + mBackStack.get(i)); 1594 } 1595 } 1596 } 1597 1598 FragmentManagerState fms = new FragmentManagerState(); 1599 fms.mActive = active; 1600 fms.mAdded = added; 1601 fms.mBackStack = backStack; 1602 return fms; 1603 } 1604 1605 void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) { 1606 // If there is no saved state at all, then there can not be 1607 // any nonConfig fragments either, so that is that. 1608 if (state == null) return; 1609 FragmentManagerState fms = (FragmentManagerState)state; 1610 if (fms.mActive == null) return; 1611 1612 // First re-attach any non-config instances we are retaining back 1613 // to their saved state, so we don't try to instantiate them again. 1614 if (nonConfig != null) { 1615 for (int i=0; i<nonConfig.size(); i++) { 1616 Fragment f = nonConfig.get(i); 1617 if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f); 1618 FragmentState fs = fms.mActive[f.mIndex]; 1619 fs.mInstance = f; 1620 f.mSavedViewState = null; 1621 f.mBackStackNesting = 0; 1622 f.mInLayout = false; 1623 f.mAdded = false; 1624 if (fs.mSavedFragmentState != null) { 1625 fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader()); 1626 f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray( 1627 FragmentManagerImpl.VIEW_STATE_TAG); 1628 } 1629 } 1630 } 1631 1632 // Build the full list of active fragments, instantiating them from 1633 // their saved state. 1634 mActive = new ArrayList<Fragment>(fms.mActive.length); 1635 if (mAvailIndices != null) { 1636 mAvailIndices.clear(); 1637 } 1638 for (int i=0; i<fms.mActive.length; i++) { 1639 FragmentState fs = fms.mActive[i]; 1640 if (fs != null) { 1641 Fragment f = fs.instantiate(mActivity); 1642 if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": " + f); 1643 mActive.add(f); 1644 // Now that the fragment is instantiated (or came from being 1645 // retained above), clear mInstance in case we end up re-restoring 1646 // from this FragmentState again. 1647 fs.mInstance = null; 1648 } else { 1649 if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": (null)"); 1650 mActive.add(null); 1651 if (mAvailIndices == null) { 1652 mAvailIndices = new ArrayList<Integer>(); 1653 } 1654 if (DEBUG) Log.v(TAG, "restoreAllState: adding avail #" + i); 1655 mAvailIndices.add(i); 1656 } 1657 } 1658 1659 // Update the target of all retained fragments. 1660 if (nonConfig != null) { 1661 for (int i=0; i<nonConfig.size(); i++) { 1662 Fragment f = nonConfig.get(i); 1663 if (f.mTarget != null) { 1664 if (f.mTarget.mIndex < mActive.size()) { 1665 f.mTarget = mActive.get(f.mTarget.mIndex); 1666 } else { 1667 Log.w(TAG, "Re-attaching retained fragment " + f 1668 + " target no longer exists: " + f.mTarget); 1669 f.mTarget = null; 1670 } 1671 } 1672 } 1673 } 1674 1675 // Build the list of currently added fragments. 1676 if (fms.mAdded != null) { 1677 mAdded = new ArrayList<Fragment>(fms.mAdded.length); 1678 for (int i=0; i<fms.mAdded.length; i++) { 1679 Fragment f = mActive.get(fms.mAdded[i]); 1680 if (f == null) { 1681 throw new IllegalStateException( 1682 "No instantiated fragment for index #" + fms.mAdded[i]); 1683 } 1684 f.mAdded = true; 1685 f.mImmediateActivity = mActivity; 1686 if (DEBUG) Log.v(TAG, "restoreAllState: making added #" + i + ": " + f); 1687 mAdded.add(f); 1688 } 1689 } else { 1690 mAdded = null; 1691 } 1692 1693 // Build the back stack. 1694 if (fms.mBackStack != null) { 1695 mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length); 1696 for (int i=0; i<fms.mBackStack.length; i++) { 1697 BackStackRecord bse = fms.mBackStack[i].instantiate(this); 1698 if (DEBUG) Log.v(TAG, "restoreAllState: adding bse #" + i 1699 + " (index " + bse.mIndex + "): " + bse); 1700 mBackStack.add(bse); 1701 if (bse.mIndex >= 0) { 1702 setBackStackIndex(bse.mIndex, bse); 1703 } 1704 } 1705 } else { 1706 mBackStack = null; 1707 } 1708 } 1709 1710 public void attachActivity(FragmentActivity activity) { 1711 if (mActivity != null) throw new IllegalStateException(); 1712 mActivity = activity; 1713 } 1714 1715 public void noteStateNotSaved() { 1716 mStateSaved = false; 1717 } 1718 1719 public void dispatchCreate() { 1720 mStateSaved = false; 1721 moveToState(Fragment.CREATED, false); 1722 } 1723 1724 public void dispatchActivityCreated() { 1725 mStateSaved = false; 1726 moveToState(Fragment.ACTIVITY_CREATED, false); 1727 } 1728 1729 public void dispatchStart() { 1730 mStateSaved = false; 1731 moveToState(Fragment.STARTED, false); 1732 } 1733 1734 public void dispatchResume() { 1735 mStateSaved = false; 1736 moveToState(Fragment.RESUMED, false); 1737 } 1738 1739 public void dispatchPause() { 1740 moveToState(Fragment.STARTED, false); 1741 } 1742 1743 public void dispatchStop() { 1744 // See saveAllState() for the explanation of this. We do this for 1745 // all platform versions, to keep our behavior more consistent between 1746 // them. 1747 mStateSaved = true; 1748 1749 moveToState(Fragment.STOPPED, false); 1750 } 1751 1752 public void dispatchReallyStop(boolean retaining) { 1753 if (mActive != null) { 1754 for (int i=0; i<mAdded.size(); i++) { 1755 Fragment f = mAdded.get(i); 1756 if (f != null) { 1757 f.performReallyStop(retaining); 1758 } 1759 } 1760 } 1761 } 1762 1763 public void dispatchDestroy() { 1764 mDestroyed = true; 1765 moveToState(Fragment.INITIALIZING, false); 1766 mActivity = null; 1767 } 1768 1769 public void dispatchConfigurationChanged(Configuration newConfig) { 1770 if (mActive != null) { 1771 for (int i=0; i<mAdded.size(); i++) { 1772 Fragment f = mAdded.get(i); 1773 if (f != null) { 1774 f.onConfigurationChanged(newConfig); 1775 } 1776 } 1777 } 1778 } 1779 1780 public void dispatchLowMemory() { 1781 if (mActive != null) { 1782 for (int i=0; i<mAdded.size(); i++) { 1783 Fragment f = mAdded.get(i); 1784 if (f != null) { 1785 f.onLowMemory(); 1786 } 1787 } 1788 } 1789 } 1790 1791 public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) { 1792 boolean show = false; 1793 ArrayList<Fragment> newMenus = null; 1794 if (mActive != null) { 1795 for (int i=0; i<mAdded.size(); i++) { 1796 Fragment f = mAdded.get(i); 1797 if (f != null && !f.mHidden && f.mHasMenu) { 1798 show = true; 1799 f.onCreateOptionsMenu(menu, inflater); 1800 if (newMenus == null) { 1801 newMenus = new ArrayList<Fragment>(); 1802 } 1803 newMenus.add(f); 1804 } 1805 } 1806 } 1807 1808 if (mCreatedMenus != null) { 1809 for (int i=0; i<mCreatedMenus.size(); i++) { 1810 Fragment f = mCreatedMenus.get(i); 1811 if (newMenus == null || !newMenus.contains(f)) { 1812 f.onDestroyOptionsMenu(); 1813 } 1814 } 1815 } 1816 1817 mCreatedMenus = newMenus; 1818 1819 return show; 1820 } 1821 1822 public boolean dispatchPrepareOptionsMenu(Menu menu) { 1823 boolean show = false; 1824 if (mActive != null) { 1825 for (int i=0; i<mAdded.size(); i++) { 1826 Fragment f = mAdded.get(i); 1827 if (f != null && !f.mHidden && f.mHasMenu) { 1828 show = true; 1829 f.onPrepareOptionsMenu(menu); 1830 } 1831 } 1832 } 1833 return show; 1834 } 1835 1836 public boolean dispatchOptionsItemSelected(MenuItem item) { 1837 if (mActive != null) { 1838 for (int i=0; i<mAdded.size(); i++) { 1839 Fragment f = mAdded.get(i); 1840 if (f != null && !f.mHidden && f.mHasMenu) { 1841 if (f.onOptionsItemSelected(item)) { 1842 return true; 1843 } 1844 } 1845 } 1846 } 1847 return false; 1848 } 1849 1850 public boolean dispatchContextItemSelected(MenuItem item) { 1851 if (mActive != null) { 1852 for (int i=0; i<mAdded.size(); i++) { 1853 Fragment f = mAdded.get(i); 1854 if (f != null && !f.mHidden) { 1855 if (f.onContextItemSelected(item)) { 1856 return true; 1857 } 1858 } 1859 } 1860 } 1861 return false; 1862 } 1863 1864 public void dispatchOptionsMenuClosed(Menu menu) { 1865 if (mActive != null) { 1866 for (int i=0; i<mAdded.size(); i++) { 1867 Fragment f = mAdded.get(i); 1868 if (f != null && !f.mHidden && f.mHasMenu) { 1869 f.onOptionsMenuClosed(menu); 1870 } 1871 } 1872 } 1873 } 1874 1875 public static int reverseTransit(int transit) { 1876 int rev = 0; 1877 switch (transit) { 1878 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 1879 rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; 1880 break; 1881 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 1882 rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN; 1883 break; 1884 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 1885 rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE; 1886 break; 1887 } 1888 return rev; 1889 1890 } 1891 1892 public static final int ANIM_STYLE_OPEN_ENTER = 1; 1893 public static final int ANIM_STYLE_OPEN_EXIT = 2; 1894 public static final int ANIM_STYLE_CLOSE_ENTER = 3; 1895 public static final int ANIM_STYLE_CLOSE_EXIT = 4; 1896 public static final int ANIM_STYLE_FADE_ENTER = 5; 1897 public static final int ANIM_STYLE_FADE_EXIT = 6; 1898 1899 public static int transitToStyleIndex(int transit, boolean enter) { 1900 int animAttr = -1; 1901 switch (transit) { 1902 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 1903 animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT; 1904 break; 1905 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 1906 animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT; 1907 break; 1908 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 1909 animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT; 1910 break; 1911 } 1912 return animAttr; 1913 } 1914} 1915