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