FragmentManager.java revision be2c79d9a5439922030d2a3846c81c61f0e16912
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 static final String USER_VISIBLE_HINT_TAG = "android:user_visible_hint"; 387 388 ArrayList<Runnable> mPendingActions; 389 Runnable[] mTmpActions; 390 boolean mExecutingActions; 391 392 ArrayList<Fragment> mActive; 393 ArrayList<Fragment> mAdded; 394 ArrayList<Integer> mAvailIndices; 395 ArrayList<BackStackRecord> mBackStack; 396 ArrayList<Fragment> mCreatedMenus; 397 398 // Must be accessed while locked. 399 ArrayList<BackStackRecord> mBackStackIndices; 400 ArrayList<Integer> mAvailBackStackIndices; 401 402 ArrayList<OnBackStackChangedListener> mBackStackChangeListeners; 403 404 int mCurState = Fragment.INITIALIZING; 405 FragmentActivity mActivity; 406 407 boolean mNeedMenuInvalidate; 408 boolean mStateSaved; 409 boolean mDestroyed; 410 String mNoTransactionsBecause; 411 boolean mHavePendingDeferredStart; 412 413 // Temporary vars for state save and restore. 414 Bundle mStateBundle = null; 415 SparseArray<Parcelable> mStateArray = null; 416 417 Runnable mExecCommit = new Runnable() { 418 @Override 419 public void run() { 420 execPendingActions(); 421 } 422 }; 423 424 @Override 425 public FragmentTransaction beginTransaction() { 426 return new BackStackRecord(this); 427 } 428 429 @Override 430 public boolean executePendingTransactions() { 431 return execPendingActions(); 432 } 433 434 @Override 435 public void popBackStack() { 436 enqueueAction(new Runnable() { 437 @Override public void run() { 438 popBackStackState(mActivity.mHandler, null, -1, 0); 439 } 440 }, false); 441 } 442 443 @Override 444 public boolean popBackStackImmediate() { 445 checkStateLoss(); 446 executePendingTransactions(); 447 return popBackStackState(mActivity.mHandler, null, -1, 0); 448 } 449 450 @Override 451 public void popBackStack(final String name, final int flags) { 452 enqueueAction(new Runnable() { 453 @Override public void run() { 454 popBackStackState(mActivity.mHandler, name, -1, flags); 455 } 456 }, false); 457 } 458 459 @Override 460 public boolean popBackStackImmediate(String name, int flags) { 461 checkStateLoss(); 462 executePendingTransactions(); 463 return popBackStackState(mActivity.mHandler, name, -1, flags); 464 } 465 466 @Override 467 public void popBackStack(final int id, final int flags) { 468 if (id < 0) { 469 throw new IllegalArgumentException("Bad id: " + id); 470 } 471 enqueueAction(new Runnable() { 472 @Override public void run() { 473 popBackStackState(mActivity.mHandler, null, id, flags); 474 } 475 }, false); 476 } 477 478 @Override 479 public boolean popBackStackImmediate(int id, int flags) { 480 checkStateLoss(); 481 executePendingTransactions(); 482 if (id < 0) { 483 throw new IllegalArgumentException("Bad id: " + id); 484 } 485 return popBackStackState(mActivity.mHandler, null, id, flags); 486 } 487 488 @Override 489 public int getBackStackEntryCount() { 490 return mBackStack != null ? mBackStack.size() : 0; 491 } 492 493 @Override 494 public BackStackEntry getBackStackEntryAt(int index) { 495 return mBackStack.get(index); 496 } 497 498 @Override 499 public void addOnBackStackChangedListener(OnBackStackChangedListener listener) { 500 if (mBackStackChangeListeners == null) { 501 mBackStackChangeListeners = new ArrayList<OnBackStackChangedListener>(); 502 } 503 mBackStackChangeListeners.add(listener); 504 } 505 506 @Override 507 public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) { 508 if (mBackStackChangeListeners != null) { 509 mBackStackChangeListeners.remove(listener); 510 } 511 } 512 513 @Override 514 public void putFragment(Bundle bundle, String key, Fragment fragment) { 515 if (fragment.mIndex < 0) { 516 throw new IllegalStateException("Fragment " + fragment 517 + " is not currently in the FragmentManager"); 518 } 519 bundle.putInt(key, fragment.mIndex); 520 } 521 522 @Override 523 public Fragment getFragment(Bundle bundle, String key) { 524 int index = bundle.getInt(key, -1); 525 if (index == -1) { 526 return null; 527 } 528 if (index >= mActive.size()) { 529 throw new IllegalStateException("Fragement no longer exists for key " 530 + key + ": index " + index); 531 } 532 Fragment f = mActive.get(index); 533 if (f == null) { 534 throw new IllegalStateException("Fragement no longer exists for key " 535 + key + ": index " + index); 536 } 537 return f; 538 } 539 540 @Override 541 public Fragment.SavedState saveFragmentInstanceState(Fragment fragment) { 542 if (fragment.mIndex < 0) { 543 throw new IllegalStateException("Fragment " + fragment 544 + " is not currently in the FragmentManager"); 545 } 546 if (fragment.mState > Fragment.INITIALIZING) { 547 Bundle result = saveFragmentBasicState(fragment); 548 return result != null ? new Fragment.SavedState(result) : null; 549 } 550 return null; 551 } 552 553 @Override 554 public String toString() { 555 StringBuilder sb = new StringBuilder(128); 556 sb.append("FragmentManager{"); 557 sb.append(Integer.toHexString(System.identityHashCode(this))); 558 sb.append(" in "); 559 DebugUtils.buildShortClassTag(mActivity, sb); 560 sb.append("}}"); 561 return sb.toString(); 562 } 563 564 @Override 565 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 566 String innerPrefix = prefix + " "; 567 568 int N; 569 if (mActive != null) { 570 N = mActive.size(); 571 if (N > 0) { 572 writer.print(prefix); writer.print("Active Fragments in "); 573 writer.print(Integer.toHexString(System.identityHashCode(this))); 574 writer.println(":"); 575 for (int i=0; i<N; i++) { 576 Fragment f = mActive.get(i); 577 writer.print(prefix); writer.print(" #"); writer.print(i); 578 writer.print(": "); writer.println(f); 579 if (f != null) { 580 f.dump(innerPrefix, fd, writer, args); 581 } 582 } 583 } 584 } 585 586 if (mAdded != null) { 587 N = mAdded.size(); 588 if (N > 0) { 589 writer.print(prefix); writer.println("Added Fragments:"); 590 for (int i=0; i<N; i++) { 591 Fragment f = mAdded.get(i); 592 writer.print(prefix); writer.print(" #"); writer.print(i); 593 writer.print(": "); writer.println(f.toString()); 594 } 595 } 596 } 597 598 if (mCreatedMenus != null) { 599 N = mCreatedMenus.size(); 600 if (N > 0) { 601 writer.print(prefix); writer.println("Fragments Created Menus:"); 602 for (int i=0; i<N; i++) { 603 Fragment f = mCreatedMenus.get(i); 604 writer.print(prefix); writer.print(" #"); writer.print(i); 605 writer.print(": "); writer.println(f.toString()); 606 } 607 } 608 } 609 610 if (mBackStack != null) { 611 N = mBackStack.size(); 612 if (N > 0) { 613 writer.print(prefix); writer.println("Back Stack:"); 614 for (int i=0; i<N; i++) { 615 BackStackRecord bs = mBackStack.get(i); 616 writer.print(prefix); writer.print(" #"); writer.print(i); 617 writer.print(": "); writer.println(bs.toString()); 618 bs.dump(innerPrefix, fd, writer, args); 619 } 620 } 621 } 622 623 synchronized (this) { 624 if (mBackStackIndices != null) { 625 N = mBackStackIndices.size(); 626 if (N > 0) { 627 writer.print(prefix); writer.println("Back Stack Indices:"); 628 for (int i=0; i<N; i++) { 629 BackStackRecord bs = mBackStackIndices.get(i); 630 writer.print(prefix); writer.print(" #"); writer.print(i); 631 writer.print(": "); writer.println(bs); 632 } 633 } 634 } 635 636 if (mAvailBackStackIndices != null && mAvailBackStackIndices.size() > 0) { 637 writer.print(prefix); writer.print("mAvailBackStackIndices: "); 638 writer.println(Arrays.toString(mAvailBackStackIndices.toArray())); 639 } 640 } 641 642 if (mPendingActions != null) { 643 N = mPendingActions.size(); 644 if (N > 0) { 645 writer.print(prefix); writer.println("Pending Actions:"); 646 for (int i=0; i<N; i++) { 647 Runnable r = mPendingActions.get(i); 648 writer.print(prefix); writer.print(" #"); writer.print(i); 649 writer.print(": "); writer.println(r); 650 } 651 } 652 } 653 654 writer.print(prefix); writer.println("FragmentManager misc state:"); 655 writer.print(prefix); writer.print(" mCurState="); writer.print(mCurState); 656 writer.print(" mStateSaved="); writer.print(mStateSaved); 657 writer.print(" mDestroyed="); writer.println(mDestroyed); 658 if (mNeedMenuInvalidate) { 659 writer.print(prefix); writer.print(" mNeedMenuInvalidate="); 660 writer.println(mNeedMenuInvalidate); 661 } 662 if (mNoTransactionsBecause != null) { 663 writer.print(prefix); writer.print(" mNoTransactionsBecause="); 664 writer.println(mNoTransactionsBecause); 665 } 666 if (mAvailIndices != null && mAvailIndices.size() > 0) { 667 writer.print(prefix); writer.print(" mAvailIndices: "); 668 writer.println(Arrays.toString(mAvailIndices.toArray())); 669 } 670 } 671 672 static final Interpolator DECELERATE_QUINT = new DecelerateInterpolator(2.5f); 673 static final Interpolator DECELERATE_CUBIC = new DecelerateInterpolator(1.5f); 674 static final Interpolator ACCELERATE_QUINT = new AccelerateInterpolator(2.5f); 675 static final Interpolator ACCELERATE_CUBIC = new AccelerateInterpolator(1.5f); 676 677 static final int ANIM_DUR = 220; 678 679 static Animation makeOpenCloseAnimation(Context context, float startScale, 680 float endScale, float startAlpha, float endAlpha) { 681 AnimationSet set = new AnimationSet(false); 682 ScaleAnimation scale = new ScaleAnimation(startScale, endScale, startScale, endScale, 683 Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f); 684 scale.setInterpolator(DECELERATE_QUINT); 685 scale.setDuration(ANIM_DUR); 686 set.addAnimation(scale); 687 AlphaAnimation alpha = new AlphaAnimation(startAlpha, endAlpha); 688 alpha.setInterpolator(DECELERATE_CUBIC); 689 alpha.setDuration(ANIM_DUR); 690 set.addAnimation(alpha); 691 return set; 692 } 693 694 static Animation makeFadeAnimation(Context context, float start, float end) { 695 AlphaAnimation anim = new AlphaAnimation(start, end); 696 anim.setInterpolator(DECELERATE_CUBIC); 697 anim.setDuration(ANIM_DUR); 698 return anim; 699 } 700 701 Animation loadAnimation(Fragment fragment, int transit, boolean enter, 702 int transitionStyle) { 703 Animation animObj = fragment.onCreateAnimation(transit, enter, 704 fragment.mNextAnim); 705 if (animObj != null) { 706 return animObj; 707 } 708 709 if (fragment.mNextAnim != 0) { 710 Animation anim = AnimationUtils.loadAnimation(mActivity, fragment.mNextAnim); 711 if (anim != null) { 712 return anim; 713 } 714 } 715 716 if (transit == 0) { 717 return null; 718 } 719 720 int styleIndex = transitToStyleIndex(transit, enter); 721 if (styleIndex < 0) { 722 return null; 723 } 724 725 switch (styleIndex) { 726 case ANIM_STYLE_OPEN_ENTER: 727 return makeOpenCloseAnimation(mActivity, 1.125f, 1.0f, 0, 1); 728 case ANIM_STYLE_OPEN_EXIT: 729 return makeOpenCloseAnimation(mActivity, 1.0f, .975f, 1, 0); 730 case ANIM_STYLE_CLOSE_ENTER: 731 return makeOpenCloseAnimation(mActivity, .975f, 1.0f, 0, 1); 732 case ANIM_STYLE_CLOSE_EXIT: 733 return makeOpenCloseAnimation(mActivity, 1.0f, 1.075f, 1, 0); 734 case ANIM_STYLE_FADE_ENTER: 735 return makeFadeAnimation(mActivity, 0, 1); 736 case ANIM_STYLE_FADE_EXIT: 737 return makeFadeAnimation(mActivity, 1, 0); 738 } 739 740 if (transitionStyle == 0 && mActivity.getWindow() != null) { 741 transitionStyle = mActivity.getWindow().getAttributes().windowAnimations; 742 } 743 if (transitionStyle == 0) { 744 return null; 745 } 746 747 //TypedArray attrs = mActivity.obtainStyledAttributes(transitionStyle, 748 // com.android.internal.R.styleable.FragmentAnimation); 749 //int anim = attrs.getResourceId(styleIndex, 0); 750 //attrs.recycle(); 751 752 //if (anim == 0) { 753 // return null; 754 //} 755 756 //return AnimatorInflater.loadAnimator(mActivity, anim); 757 return null; 758 } 759 760 public void performPendingDeferredStart(Fragment f) { 761 if (f.mDeferStart) { 762 if (mExecutingActions) { 763 // Wait until we're done executing our pending transactions 764 mHavePendingDeferredStart = true; 765 return; 766 } 767 f.mDeferStart = false; 768 moveToState(f, mCurState, 0, 0); 769 } 770 } 771 772 void moveToState(Fragment f, int newState, int transit, int transitionStyle) { 773 // Fragments that are not currently added will sit in the onCreate() state. 774 if (!f.mAdded && newState > Fragment.CREATED) { 775 newState = Fragment.CREATED; 776 } 777 if (f.mRemoving && newState > f.mState) { 778 // While removing a fragment, we can't change it to a higher state. 779 newState = f.mState; 780 } 781 // Defer start if requested; don't allow it to move to STARTED or higher 782 // if it's not already started. 783 if (f.mDeferStart && f.mState < Fragment.STARTED && newState > Fragment.STOPPED) { 784 newState = Fragment.STOPPED; 785 } 786 if (f.mState < newState) { 787 // For fragments that are created from a layout, when restoring from 788 // state we don't want to allow them to be created until they are 789 // being reloaded from the layout. 790 if (f.mFromLayout && !f.mInLayout) { 791 return; 792 } 793 if (f.mAnimatingAway != null) { 794 // The fragment is currently being animated... but! Now we 795 // want to move our state back up. Give up on waiting for the 796 // animation, move to whatever the final state should be once 797 // the animation is done, and then we can proceed from there. 798 f.mAnimatingAway = null; 799 moveToState(f, f.mStateAfterAnimating, 0, 0); 800 } 801 switch (f.mState) { 802 case Fragment.INITIALIZING: 803 if (DEBUG) Log.v(TAG, "moveto CREATED: " + f); 804 if (f.mSavedFragmentState != null) { 805 f.mSavedViewState = f.mSavedFragmentState.getSparseParcelableArray( 806 FragmentManagerImpl.VIEW_STATE_TAG); 807 f.mTarget = getFragment(f.mSavedFragmentState, 808 FragmentManagerImpl.TARGET_STATE_TAG); 809 if (f.mTarget != null) { 810 f.mTargetRequestCode = f.mSavedFragmentState.getInt( 811 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 0); 812 } 813 f.mUserVisibleHint = f.mSavedFragmentState.getBoolean( 814 FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true); 815 if (!f.mUserVisibleHint) { 816 f.mDeferStart = true; 817 if (newState > Fragment.STOPPED) { 818 newState = Fragment.STOPPED; 819 } 820 } 821 } 822 f.mActivity = mActivity; 823 f.mFragmentManager = mActivity.mFragments; 824 f.mCalled = false; 825 f.onAttach(mActivity); 826 if (!f.mCalled) { 827 throw new SuperNotCalledException("Fragment " + f 828 + " did not call through to super.onAttach()"); 829 } 830 mActivity.onAttachFragment(f); 831 832 if (!f.mRetaining) { 833 f.mCalled = false; 834 f.onCreate(f.mSavedFragmentState); 835 if (!f.mCalled) { 836 throw new SuperNotCalledException("Fragment " + f 837 + " did not call through to super.onCreate()"); 838 } 839 } 840 f.mRetaining = false; 841 if (f.mFromLayout) { 842 // For fragments that are part of the content view 843 // layout, we need to instantiate the view immediately 844 // and the inflater will take care of adding it. 845 f.mView = f.onCreateView(f.getLayoutInflater(f.mSavedFragmentState), 846 null, f.mSavedFragmentState); 847 if (f.mView != null) { 848 f.mInnerView = f.mView; 849 f.mView = NoSaveStateFrameLayout.wrap(f.mView); 850 if (f.mHidden) f.mView.setVisibility(View.GONE); 851 f.onViewCreated(f.mView, f.mSavedFragmentState); 852 } else { 853 f.mInnerView = null; 854 } 855 } 856 case Fragment.CREATED: 857 if (newState > Fragment.CREATED) { 858 if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f); 859 if (!f.mFromLayout) { 860 ViewGroup container = null; 861 if (f.mContainerId != 0) { 862 container = (ViewGroup)mActivity.findViewById(f.mContainerId); 863 if (container == null && !f.mRestored) { 864 throw new IllegalArgumentException("No view found for id 0x" 865 + Integer.toHexString(f.mContainerId) 866 + " for fragment " + f); 867 } 868 } 869 f.mContainer = container; 870 f.mView = f.onCreateView(f.getLayoutInflater(f.mSavedFragmentState), 871 container, f.mSavedFragmentState); 872 if (f.mView != null) { 873 f.mInnerView = f.mView; 874 f.mView = NoSaveStateFrameLayout.wrap(f.mView); 875 if (container != null) { 876 Animation anim = loadAnimation(f, transit, true, 877 transitionStyle); 878 if (anim != null) { 879 f.mView.startAnimation(anim); 880 } 881 container.addView(f.mView); 882 } 883 if (f.mHidden) f.mView.setVisibility(View.GONE); 884 f.onViewCreated(f.mView, f.mSavedFragmentState); 885 } else { 886 f.mInnerView = null; 887 } 888 } 889 890 f.mCalled = false; 891 f.onActivityCreated(f.mSavedFragmentState); 892 if (!f.mCalled) { 893 throw new SuperNotCalledException("Fragment " + f 894 + " did not call through to super.onActivityCreated()"); 895 } 896 if (f.mView != null) { 897 f.restoreViewState(); 898 } 899 f.mSavedFragmentState = null; 900 } 901 case Fragment.ACTIVITY_CREATED: 902 case Fragment.STOPPED: 903 if (newState > Fragment.STOPPED) { 904 if (DEBUG) Log.v(TAG, "moveto STARTED: " + f); 905 f.mCalled = false; 906 f.performStart(); 907 if (!f.mCalled) { 908 throw new SuperNotCalledException("Fragment " + f 909 + " did not call through to super.onStart()"); 910 } 911 } 912 case Fragment.STARTED: 913 if (newState > Fragment.STARTED) { 914 if (DEBUG) Log.v(TAG, "moveto RESUMED: " + f); 915 f.mCalled = false; 916 f.mResumed = true; 917 f.onResume(); 918 if (!f.mCalled) { 919 throw new SuperNotCalledException("Fragment " + f 920 + " did not call through to super.onResume()"); 921 } 922 f.mSavedFragmentState = null; 923 f.mSavedViewState = null; 924 } 925 } 926 } else if (f.mState > newState) { 927 switch (f.mState) { 928 case Fragment.RESUMED: 929 if (newState < Fragment.RESUMED) { 930 if (DEBUG) Log.v(TAG, "movefrom RESUMED: " + f); 931 f.mCalled = false; 932 f.onPause(); 933 if (!f.mCalled) { 934 throw new SuperNotCalledException("Fragment " + f 935 + " did not call through to super.onPause()"); 936 } 937 f.mResumed = false; 938 } 939 case Fragment.STARTED: 940 if (newState < Fragment.STARTED) { 941 if (DEBUG) Log.v(TAG, "movefrom STARTED: " + f); 942 f.mCalled = false; 943 f.performStop(); 944 if (!f.mCalled) { 945 throw new SuperNotCalledException("Fragment " + f 946 + " did not call through to super.onStop()"); 947 } 948 } 949 case Fragment.STOPPED: 950 if (newState < Fragment.STOPPED) { 951 if (DEBUG) Log.v(TAG, "movefrom STOPPED: " + f); 952 f.performReallyStop(); 953 } 954 case Fragment.ACTIVITY_CREATED: 955 if (newState < Fragment.ACTIVITY_CREATED) { 956 if (DEBUG) Log.v(TAG, "movefrom ACTIVITY_CREATED: " + f); 957 if (f.mView != null) { 958 // Need to save the current view state if not 959 // done already. 960 if (!mActivity.isFinishing() && f.mSavedViewState == null) { 961 saveFragmentViewState(f); 962 } 963 } 964 f.mCalled = false; 965 f.performDestroyView(); 966 if (!f.mCalled) { 967 throw new SuperNotCalledException("Fragment " + f 968 + " did not call through to super.onDestroyView()"); 969 } 970 if (f.mView != null && f.mContainer != null) { 971 Animation anim = null; 972 if (mCurState > Fragment.INITIALIZING && !mDestroyed) { 973 anim = loadAnimation(f, transit, false, 974 transitionStyle); 975 } 976 if (anim != null) { 977 final Fragment fragment = f; 978 f.mAnimatingAway = f.mView; 979 f.mStateAfterAnimating = newState; 980 anim.setAnimationListener(new AnimationListener() { 981 @Override 982 public void onAnimationEnd(Animation animation) { 983 if (fragment.mAnimatingAway != null) { 984 fragment.mAnimatingAway = null; 985 moveToState(fragment, fragment.mStateAfterAnimating, 986 0, 0); 987 } 988 } 989 @Override 990 public void onAnimationRepeat(Animation animation) { 991 } 992 @Override 993 public void onAnimationStart(Animation animation) { 994 } 995 }); 996 f.mView.startAnimation(anim); 997 } 998 f.mContainer.removeView(f.mView); 999 } 1000 f.mContainer = null; 1001 f.mView = null; 1002 f.mInnerView = null; 1003 } 1004 case Fragment.CREATED: 1005 if (newState < Fragment.CREATED) { 1006 if (mDestroyed) { 1007 if (f.mAnimatingAway != null) { 1008 // The fragment's containing activity is 1009 // being destroyed, but this fragment is 1010 // currently animating away. Stop the 1011 // animation right now -- it is not needed, 1012 // and we can't wait any more on destroying 1013 // the fragment. 1014 View v = f.mAnimatingAway; 1015 f.mAnimatingAway = null; 1016 v.clearAnimation(); 1017 } 1018 } 1019 if (f.mAnimatingAway != null) { 1020 // We are waiting for the fragment's view to finish 1021 // animating away. Just make a note of the state 1022 // the fragment now should move to once the animation 1023 // is done. 1024 f.mStateAfterAnimating = newState; 1025 newState = Fragment.CREATED; 1026 } else { 1027 if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f); 1028 if (!f.mRetaining) { 1029 f.mCalled = false; 1030 f.onDestroy(); 1031 if (!f.mCalled) { 1032 throw new SuperNotCalledException("Fragment " + f 1033 + " did not call through to super.onDestroy()"); 1034 } 1035 } 1036 1037 f.mCalled = false; 1038 f.onDetach(); 1039 if (!f.mCalled) { 1040 throw new SuperNotCalledException("Fragment " + f 1041 + " did not call through to super.onDetach()"); 1042 } 1043 if (!f.mRetaining) { 1044 makeInactive(f); 1045 } else { 1046 f.mActivity = null; 1047 f.mFragmentManager = null; 1048 } 1049 } 1050 } 1051 } 1052 } 1053 1054 f.mState = newState; 1055 } 1056 1057 void moveToState(Fragment f) { 1058 moveToState(f, mCurState, 0, 0); 1059 } 1060 1061 void moveToState(int newState, boolean always) { 1062 moveToState(newState, 0, 0, always); 1063 } 1064 1065 void moveToState(int newState, int transit, int transitStyle, boolean always) { 1066 if (mActivity == null && newState != Fragment.INITIALIZING) { 1067 throw new IllegalStateException("No activity"); 1068 } 1069 1070 if (!always && mCurState == newState) { 1071 return; 1072 } 1073 1074 mCurState = newState; 1075 if (mActive != null) { 1076 boolean loadersRunning = false; 1077 for (int i=0; i<mActive.size(); i++) { 1078 Fragment f = mActive.get(i); 1079 if (f != null) { 1080 moveToState(f, newState, transit, transitStyle); 1081 if (f.mLoaderManager != null) { 1082 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 1083 } 1084 } 1085 } 1086 1087 if (!loadersRunning) { 1088 startPendingDeferredFragments(); 1089 } 1090 1091 if (mNeedMenuInvalidate && mActivity != null && mCurState == Fragment.RESUMED) { 1092 mActivity.supportInvalidateOptionsMenu(); 1093 mNeedMenuInvalidate = false; 1094 } 1095 } 1096 } 1097 1098 void startPendingDeferredFragments() { 1099 if (mActive == null) return; 1100 1101 for (int i=0; i<mActive.size(); i++) { 1102 Fragment f = mActive.get(i); 1103 if (f != null) { 1104 performPendingDeferredStart(f); 1105 } 1106 } 1107 } 1108 1109 void makeActive(Fragment f) { 1110 if (f.mIndex >= 0) { 1111 return; 1112 } 1113 1114 if (mAvailIndices == null || mAvailIndices.size() <= 0) { 1115 if (mActive == null) { 1116 mActive = new ArrayList<Fragment>(); 1117 } 1118 f.setIndex(mActive.size()); 1119 mActive.add(f); 1120 1121 } else { 1122 f.setIndex(mAvailIndices.remove(mAvailIndices.size()-1)); 1123 mActive.set(f.mIndex, f); 1124 } 1125 if (DEBUG) Log.v(TAG, "Allocated fragment index " + f); 1126 } 1127 1128 void makeInactive(Fragment f) { 1129 if (f.mIndex < 0) { 1130 return; 1131 } 1132 1133 if (DEBUG) Log.v(TAG, "Freeing fragment index " + f); 1134 mActive.set(f.mIndex, null); 1135 if (mAvailIndices == null) { 1136 mAvailIndices = new ArrayList<Integer>(); 1137 } 1138 mAvailIndices.add(f.mIndex); 1139 mActivity.invalidateSupportFragmentIndex(f.mIndex); 1140 f.initState(); 1141 } 1142 1143 public void addFragment(Fragment fragment, boolean moveToStateNow) { 1144 if (mAdded == null) { 1145 mAdded = new ArrayList<Fragment>(); 1146 } 1147 if (DEBUG) Log.v(TAG, "add: " + fragment); 1148 makeActive(fragment); 1149 if (!fragment.mDetached) { 1150 mAdded.add(fragment); 1151 fragment.mAdded = true; 1152 fragment.mRemoving = false; 1153 if (fragment.mHasMenu && fragment.mMenuVisible) { 1154 mNeedMenuInvalidate = true; 1155 } 1156 if (moveToStateNow) { 1157 moveToState(fragment); 1158 } 1159 } 1160 } 1161 1162 public void removeFragment(Fragment fragment, int transition, int transitionStyle) { 1163 if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting); 1164 final boolean inactive = !fragment.isInBackStack(); 1165 if (!fragment.mDetached || inactive) { 1166 mAdded.remove(fragment); 1167 if (fragment.mHasMenu && fragment.mMenuVisible) { 1168 mNeedMenuInvalidate = true; 1169 } 1170 fragment.mAdded = false; 1171 fragment.mRemoving = true; 1172 moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED, 1173 transition, transitionStyle); 1174 } 1175 } 1176 1177 public void hideFragment(Fragment fragment, int transition, int transitionStyle) { 1178 if (DEBUG) Log.v(TAG, "hide: " + fragment); 1179 if (!fragment.mHidden) { 1180 fragment.mHidden = true; 1181 if (fragment.mView != null) { 1182 Animation anim = loadAnimation(fragment, transition, true, 1183 transitionStyle); 1184 if (anim != null) { 1185 fragment.mView.startAnimation(anim); 1186 } 1187 fragment.mView.setVisibility(View.GONE); 1188 } 1189 if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) { 1190 mNeedMenuInvalidate = true; 1191 } 1192 fragment.onHiddenChanged(true); 1193 } 1194 } 1195 1196 public void showFragment(Fragment fragment, int transition, int transitionStyle) { 1197 if (DEBUG) Log.v(TAG, "show: " + fragment); 1198 if (fragment.mHidden) { 1199 fragment.mHidden = false; 1200 if (fragment.mView != null) { 1201 Animation anim = loadAnimation(fragment, transition, true, 1202 transitionStyle); 1203 if (anim != null) { 1204 fragment.mView.startAnimation(anim); 1205 } 1206 fragment.mView.setVisibility(View.VISIBLE); 1207 } 1208 if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) { 1209 mNeedMenuInvalidate = true; 1210 } 1211 fragment.onHiddenChanged(false); 1212 } 1213 } 1214 1215 public void detachFragment(Fragment fragment, int transition, int transitionStyle) { 1216 if (DEBUG) Log.v(TAG, "detach: " + fragment); 1217 if (!fragment.mDetached) { 1218 fragment.mDetached = true; 1219 if (fragment.mAdded) { 1220 // We are not already in back stack, so need to remove the fragment. 1221 mAdded.remove(fragment); 1222 if (fragment.mHasMenu && fragment.mMenuVisible) { 1223 mNeedMenuInvalidate = true; 1224 } 1225 fragment.mAdded = false; 1226 moveToState(fragment, Fragment.CREATED, transition, transitionStyle); 1227 } 1228 } 1229 } 1230 1231 public void attachFragment(Fragment fragment, int transition, int transitionStyle) { 1232 if (DEBUG) Log.v(TAG, "attach: " + fragment); 1233 if (fragment.mDetached) { 1234 fragment.mDetached = false; 1235 if (!fragment.mAdded) { 1236 mAdded.add(fragment); 1237 fragment.mAdded = true; 1238 if (fragment.mHasMenu && fragment.mMenuVisible) { 1239 mNeedMenuInvalidate = true; 1240 } 1241 moveToState(fragment, mCurState, transition, transitionStyle); 1242 } 1243 } 1244 } 1245 1246 public Fragment findFragmentById(int id) { 1247 if (mActive != null) { 1248 // First look through added fragments. 1249 for (int i=mAdded.size()-1; i>=0; i--) { 1250 Fragment f = mAdded.get(i); 1251 if (f != null && f.mFragmentId == id) { 1252 return f; 1253 } 1254 } 1255 // Now for any known fragment. 1256 for (int i=mActive.size()-1; i>=0; i--) { 1257 Fragment f = mActive.get(i); 1258 if (f != null && f.mFragmentId == id) { 1259 return f; 1260 } 1261 } 1262 } 1263 return null; 1264 } 1265 1266 public Fragment findFragmentByTag(String tag) { 1267 if (mActive != null && tag != null) { 1268 // First look through added fragments. 1269 for (int i=mAdded.size()-1; i>=0; i--) { 1270 Fragment f = mAdded.get(i); 1271 if (f != null && tag.equals(f.mTag)) { 1272 return f; 1273 } 1274 } 1275 // Now for any known fragment. 1276 for (int i=mActive.size()-1; i>=0; i--) { 1277 Fragment f = mActive.get(i); 1278 if (f != null && tag.equals(f.mTag)) { 1279 return f; 1280 } 1281 } 1282 } 1283 return null; 1284 } 1285 1286 public Fragment findFragmentByWho(String who) { 1287 if (mActive != null && who != null) { 1288 for (int i=mActive.size()-1; i>=0; i--) { 1289 Fragment f = mActive.get(i); 1290 if (f != null && who.equals(f.mWho)) { 1291 return f; 1292 } 1293 } 1294 } 1295 return null; 1296 } 1297 1298 private void checkStateLoss() { 1299 if (mStateSaved) { 1300 throw new IllegalStateException( 1301 "Can not perform this action after onSaveInstanceState"); 1302 } 1303 if (mNoTransactionsBecause != null) { 1304 throw new IllegalStateException( 1305 "Can not perform this action inside of " + mNoTransactionsBecause); 1306 } 1307 } 1308 1309 public void enqueueAction(Runnable action, boolean allowStateLoss) { 1310 if (!allowStateLoss) { 1311 checkStateLoss(); 1312 } 1313 synchronized (this) { 1314 if (mActivity == null) { 1315 throw new IllegalStateException("Activity has been destroyed"); 1316 } 1317 if (mPendingActions == null) { 1318 mPendingActions = new ArrayList<Runnable>(); 1319 } 1320 mPendingActions.add(action); 1321 if (mPendingActions.size() == 1) { 1322 mActivity.mHandler.removeCallbacks(mExecCommit); 1323 mActivity.mHandler.post(mExecCommit); 1324 } 1325 } 1326 } 1327 1328 public int allocBackStackIndex(BackStackRecord bse) { 1329 synchronized (this) { 1330 if (mAvailBackStackIndices == null || mAvailBackStackIndices.size() <= 0) { 1331 if (mBackStackIndices == null) { 1332 mBackStackIndices = new ArrayList<BackStackRecord>(); 1333 } 1334 int index = mBackStackIndices.size(); 1335 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1336 mBackStackIndices.add(bse); 1337 return index; 1338 1339 } else { 1340 int index = mAvailBackStackIndices.remove(mAvailBackStackIndices.size()-1); 1341 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1342 mBackStackIndices.set(index, bse); 1343 return index; 1344 } 1345 } 1346 } 1347 1348 public void setBackStackIndex(int index, BackStackRecord bse) { 1349 synchronized (this) { 1350 if (mBackStackIndices == null) { 1351 mBackStackIndices = new ArrayList<BackStackRecord>(); 1352 } 1353 int N = mBackStackIndices.size(); 1354 if (index < N) { 1355 if (DEBUG) Log.v(TAG, "Setting back stack index " + index + " to " + bse); 1356 mBackStackIndices.set(index, bse); 1357 } else { 1358 while (N < index) { 1359 mBackStackIndices.add(null); 1360 if (mAvailBackStackIndices == null) { 1361 mAvailBackStackIndices = new ArrayList<Integer>(); 1362 } 1363 if (DEBUG) Log.v(TAG, "Adding available back stack index " + N); 1364 mAvailBackStackIndices.add(N); 1365 N++; 1366 } 1367 if (DEBUG) Log.v(TAG, "Adding back stack index " + index + " with " + bse); 1368 mBackStackIndices.add(bse); 1369 } 1370 } 1371 } 1372 1373 public void freeBackStackIndex(int index) { 1374 synchronized (this) { 1375 mBackStackIndices.set(index, null); 1376 if (mAvailBackStackIndices == null) { 1377 mAvailBackStackIndices = new ArrayList<Integer>(); 1378 } 1379 if (DEBUG) Log.v(TAG, "Freeing back stack index " + index); 1380 mAvailBackStackIndices.add(index); 1381 } 1382 } 1383 1384 /** 1385 * Only call from main thread! 1386 */ 1387 public boolean execPendingActions() { 1388 if (mExecutingActions) { 1389 throw new IllegalStateException("Recursive entry to executePendingTransactions"); 1390 } 1391 1392 if (Looper.myLooper() != mActivity.mHandler.getLooper()) { 1393 throw new IllegalStateException("Must be called from main thread of process"); 1394 } 1395 1396 boolean didSomething = false; 1397 1398 while (true) { 1399 int numActions; 1400 1401 synchronized (this) { 1402 if (mPendingActions == null || mPendingActions.size() == 0) { 1403 break; 1404 } 1405 1406 numActions = mPendingActions.size(); 1407 if (mTmpActions == null || mTmpActions.length < numActions) { 1408 mTmpActions = new Runnable[numActions]; 1409 } 1410 mPendingActions.toArray(mTmpActions); 1411 mPendingActions.clear(); 1412 mActivity.mHandler.removeCallbacks(mExecCommit); 1413 } 1414 1415 mExecutingActions = true; 1416 for (int i=0; i<numActions; i++) { 1417 mTmpActions[i].run(); 1418 mTmpActions[i] = null; 1419 } 1420 mExecutingActions = false; 1421 didSomething = true; 1422 } 1423 1424 if (mHavePendingDeferredStart) { 1425 boolean loadersRunning = false; 1426 for (int i=0; i<mActive.size(); i++) { 1427 Fragment f = mActive.get(i); 1428 if (f != null && f.mLoaderManager != null) { 1429 loadersRunning |= f.mLoaderManager.hasRunningLoaders(); 1430 } 1431 } 1432 if (!loadersRunning) { 1433 mHavePendingDeferredStart = false; 1434 startPendingDeferredFragments(); 1435 } 1436 } 1437 return didSomething; 1438 } 1439 1440 void reportBackStackChanged() { 1441 if (mBackStackChangeListeners != null) { 1442 for (int i=0; i<mBackStackChangeListeners.size(); i++) { 1443 mBackStackChangeListeners.get(i).onBackStackChanged(); 1444 } 1445 } 1446 } 1447 1448 void addBackStackState(BackStackRecord state) { 1449 if (mBackStack == null) { 1450 mBackStack = new ArrayList<BackStackRecord>(); 1451 } 1452 mBackStack.add(state); 1453 reportBackStackChanged(); 1454 } 1455 1456 boolean popBackStackState(Handler handler, String name, int id, int flags) { 1457 if (mBackStack == null) { 1458 return false; 1459 } 1460 if (name == null && id < 0 && (flags&POP_BACK_STACK_INCLUSIVE) == 0) { 1461 int last = mBackStack.size()-1; 1462 if (last < 0) { 1463 return false; 1464 } 1465 final BackStackRecord bss = mBackStack.remove(last); 1466 bss.popFromBackStack(true); 1467 reportBackStackChanged(); 1468 } else { 1469 int index = -1; 1470 if (name != null || id >= 0) { 1471 // If a name or ID is specified, look for that place in 1472 // the stack. 1473 index = mBackStack.size()-1; 1474 while (index >= 0) { 1475 BackStackRecord bss = mBackStack.get(index); 1476 if (name != null && name.equals(bss.getName())) { 1477 break; 1478 } 1479 if (id >= 0 && id == bss.mIndex) { 1480 break; 1481 } 1482 index--; 1483 } 1484 if (index < 0) { 1485 return false; 1486 } 1487 if ((flags&POP_BACK_STACK_INCLUSIVE) != 0) { 1488 index--; 1489 // Consume all following entries that match. 1490 while (index >= 0) { 1491 BackStackRecord bss = mBackStack.get(index); 1492 if ((name != null && name.equals(bss.getName())) 1493 || (id >= 0 && id == bss.mIndex)) { 1494 index--; 1495 continue; 1496 } 1497 break; 1498 } 1499 } 1500 } 1501 if (index == mBackStack.size()-1) { 1502 return false; 1503 } 1504 final ArrayList<BackStackRecord> states 1505 = new ArrayList<BackStackRecord>(); 1506 for (int i=mBackStack.size()-1; i>index; i--) { 1507 states.add(mBackStack.remove(i)); 1508 } 1509 final int LAST = states.size()-1; 1510 for (int i=0; i<=LAST; i++) { 1511 if (DEBUG) Log.v(TAG, "Popping back stack state: " + states.get(i)); 1512 states.get(i).popFromBackStack(i == LAST); 1513 } 1514 reportBackStackChanged(); 1515 } 1516 return true; 1517 } 1518 1519 ArrayList<Fragment> retainNonConfig() { 1520 ArrayList<Fragment> fragments = null; 1521 if (mActive != null) { 1522 for (int i=0; i<mActive.size(); i++) { 1523 Fragment f = mActive.get(i); 1524 if (f != null && f.mRetainInstance) { 1525 if (fragments == null) { 1526 fragments = new ArrayList<Fragment>(); 1527 } 1528 fragments.add(f); 1529 f.mRetaining = true; 1530 f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1; 1531 if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f); 1532 } 1533 } 1534 } 1535 return fragments; 1536 } 1537 1538 void saveFragmentViewState(Fragment f) { 1539 if (f.mInnerView == null) { 1540 return; 1541 } 1542 if (mStateArray == null) { 1543 mStateArray = new SparseArray<Parcelable>(); 1544 } else { 1545 mStateArray.clear(); 1546 } 1547 f.mInnerView.saveHierarchyState(mStateArray); 1548 if (mStateArray.size() > 0) { 1549 f.mSavedViewState = mStateArray; 1550 mStateArray = null; 1551 } 1552 } 1553 1554 Bundle saveFragmentBasicState(Fragment f) { 1555 Bundle result = null; 1556 1557 if (mStateBundle == null) { 1558 mStateBundle = new Bundle(); 1559 } 1560 f.onSaveInstanceState(mStateBundle); 1561 if (!mStateBundle.isEmpty()) { 1562 result = mStateBundle; 1563 mStateBundle = null; 1564 } 1565 1566 if (f.mView != null) { 1567 saveFragmentViewState(f); 1568 } 1569 if (f.mSavedViewState != null) { 1570 if (result == null) { 1571 result = new Bundle(); 1572 } 1573 result.putSparseParcelableArray( 1574 FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState); 1575 } 1576 if (!f.mUserVisibleHint) { 1577 if (result == null) { 1578 result = new Bundle(); 1579 } 1580 // Only add this if it's not the default value 1581 result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint); 1582 } 1583 1584 return result; 1585 } 1586 1587 Parcelable saveAllState() { 1588 // Make sure all pending operations have now been executed to get 1589 // our state update-to-date. 1590 execPendingActions(); 1591 1592 if (HONEYCOMB) { 1593 // As of Honeycomb, we save state after pausing. Prior to that 1594 // it is before pausing. With fragments this is an issue, since 1595 // there are many things you may do after pausing but before 1596 // stopping that change the fragment state. For those older 1597 // devices, we will not at this point say that we have saved 1598 // the state, so we will allow them to continue doing fragment 1599 // transactions. This retains the same semantics as Honeycomb, 1600 // though you do have the risk of losing the very most recent state 1601 // if the process is killed... we'll live with that. 1602 mStateSaved = true; 1603 } 1604 1605 if (mActive == null || mActive.size() <= 0) { 1606 return null; 1607 } 1608 1609 // First collect all active fragments. 1610 int N = mActive.size(); 1611 FragmentState[] active = new FragmentState[N]; 1612 boolean haveFragments = false; 1613 for (int i=0; i<N; i++) { 1614 Fragment f = mActive.get(i); 1615 if (f != null) { 1616 haveFragments = true; 1617 1618 FragmentState fs = new FragmentState(f); 1619 active[i] = fs; 1620 1621 if (f.mState > Fragment.INITIALIZING && fs.mSavedFragmentState == null) { 1622 fs.mSavedFragmentState = saveFragmentBasicState(f); 1623 1624 if (f.mTarget != null) { 1625 if (f.mTarget.mIndex < 0) { 1626 String msg = "Failure saving state: " + f 1627 + " has target not in fragment manager: " + f.mTarget; 1628 Log.e(TAG, msg); 1629 dump(" ", null, new PrintWriter(new LogWriter(TAG)), new String[] { }); 1630 throw new IllegalStateException(msg); 1631 } 1632 if (fs.mSavedFragmentState == null) { 1633 fs.mSavedFragmentState = new Bundle(); 1634 } 1635 putFragment(fs.mSavedFragmentState, 1636 FragmentManagerImpl.TARGET_STATE_TAG, f.mTarget); 1637 if (f.mTargetRequestCode != 0) { 1638 fs.mSavedFragmentState.putInt( 1639 FragmentManagerImpl.TARGET_REQUEST_CODE_STATE_TAG, 1640 f.mTargetRequestCode); 1641 } 1642 } 1643 1644 } else { 1645 fs.mSavedFragmentState = f.mSavedFragmentState; 1646 } 1647 1648 if (DEBUG) Log.v(TAG, "Saved state of " + f + ": " 1649 + fs.mSavedFragmentState); 1650 } 1651 } 1652 1653 if (!haveFragments) { 1654 if (DEBUG) Log.v(TAG, "saveAllState: no fragments!"); 1655 return null; 1656 } 1657 1658 int[] added = null; 1659 BackStackState[] backStack = null; 1660 1661 // Build list of currently added fragments. 1662 if (mAdded != null) { 1663 N = mAdded.size(); 1664 if (N > 0) { 1665 added = new int[N]; 1666 for (int i=0; i<N; i++) { 1667 added[i] = mAdded.get(i).mIndex; 1668 if (DEBUG) Log.v(TAG, "saveAllState: adding fragment #" + i 1669 + ": " + mAdded.get(i)); 1670 } 1671 } 1672 } 1673 1674 // Now save back stack. 1675 if (mBackStack != null) { 1676 N = mBackStack.size(); 1677 if (N > 0) { 1678 backStack = new BackStackState[N]; 1679 for (int i=0; i<N; i++) { 1680 backStack[i] = new BackStackState(this, mBackStack.get(i)); 1681 if (DEBUG) Log.v(TAG, "saveAllState: adding back stack #" + i 1682 + ": " + mBackStack.get(i)); 1683 } 1684 } 1685 } 1686 1687 FragmentManagerState fms = new FragmentManagerState(); 1688 fms.mActive = active; 1689 fms.mAdded = added; 1690 fms.mBackStack = backStack; 1691 return fms; 1692 } 1693 1694 void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) { 1695 // If there is no saved state at all, then there can not be 1696 // any nonConfig fragments either, so that is that. 1697 if (state == null) return; 1698 FragmentManagerState fms = (FragmentManagerState)state; 1699 if (fms.mActive == null) return; 1700 1701 // First re-attach any non-config instances we are retaining back 1702 // to their saved state, so we don't try to instantiate them again. 1703 if (nonConfig != null) { 1704 for (int i=0; i<nonConfig.size(); i++) { 1705 Fragment f = nonConfig.get(i); 1706 if (DEBUG) Log.v(TAG, "restoreAllState: re-attaching retained " + f); 1707 FragmentState fs = fms.mActive[f.mIndex]; 1708 fs.mInstance = f; 1709 f.mSavedViewState = null; 1710 f.mBackStackNesting = 0; 1711 f.mInLayout = false; 1712 f.mAdded = false; 1713 f.mTarget = null; 1714 if (fs.mSavedFragmentState != null) { 1715 fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader()); 1716 f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray( 1717 FragmentManagerImpl.VIEW_STATE_TAG); 1718 } 1719 } 1720 } 1721 1722 // Build the full list of active fragments, instantiating them from 1723 // their saved state. 1724 mActive = new ArrayList<Fragment>(fms.mActive.length); 1725 if (mAvailIndices != null) { 1726 mAvailIndices.clear(); 1727 } 1728 for (int i=0; i<fms.mActive.length; i++) { 1729 FragmentState fs = fms.mActive[i]; 1730 if (fs != null) { 1731 Fragment f = fs.instantiate(mActivity); 1732 if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": " + f); 1733 mActive.add(f); 1734 // Now that the fragment is instantiated (or came from being 1735 // retained above), clear mInstance in case we end up re-restoring 1736 // from this FragmentState again. 1737 fs.mInstance = null; 1738 } else { 1739 if (DEBUG) Log.v(TAG, "restoreAllState: adding #" + i + ": (null)"); 1740 mActive.add(null); 1741 if (mAvailIndices == null) { 1742 mAvailIndices = new ArrayList<Integer>(); 1743 } 1744 if (DEBUG) Log.v(TAG, "restoreAllState: adding avail #" + i); 1745 mAvailIndices.add(i); 1746 } 1747 } 1748 1749 // Update the target of all retained fragments. 1750 if (nonConfig != null) { 1751 for (int i=0; i<nonConfig.size(); i++) { 1752 Fragment f = nonConfig.get(i); 1753 if (f.mTargetIndex >= 0) { 1754 if (f.mTargetIndex < mActive.size()) { 1755 f.mTarget = mActive.get(f.mTargetIndex); 1756 } else { 1757 Log.w(TAG, "Re-attaching retained fragment " + f 1758 + " target no longer exists: " + f.mTargetIndex); 1759 f.mTarget = null; 1760 } 1761 } 1762 } 1763 } 1764 1765 // Build the list of currently added fragments. 1766 if (fms.mAdded != null) { 1767 mAdded = new ArrayList<Fragment>(fms.mAdded.length); 1768 for (int i=0; i<fms.mAdded.length; i++) { 1769 Fragment f = mActive.get(fms.mAdded[i]); 1770 if (f == null) { 1771 throw new IllegalStateException( 1772 "No instantiated fragment for index #" + fms.mAdded[i]); 1773 } 1774 f.mAdded = true; 1775 if (DEBUG) Log.v(TAG, "restoreAllState: making added #" + i + ": " + f); 1776 mAdded.add(f); 1777 } 1778 } else { 1779 mAdded = null; 1780 } 1781 1782 // Build the back stack. 1783 if (fms.mBackStack != null) { 1784 mBackStack = new ArrayList<BackStackRecord>(fms.mBackStack.length); 1785 for (int i=0; i<fms.mBackStack.length; i++) { 1786 BackStackRecord bse = fms.mBackStack[i].instantiate(this); 1787 if (DEBUG) Log.v(TAG, "restoreAllState: adding bse #" + i 1788 + " (index " + bse.mIndex + "): " + bse); 1789 mBackStack.add(bse); 1790 if (bse.mIndex >= 0) { 1791 setBackStackIndex(bse.mIndex, bse); 1792 } 1793 } 1794 } else { 1795 mBackStack = null; 1796 } 1797 } 1798 1799 public void attachActivity(FragmentActivity activity) { 1800 if (mActivity != null) throw new IllegalStateException(); 1801 mActivity = activity; 1802 } 1803 1804 public void noteStateNotSaved() { 1805 mStateSaved = false; 1806 } 1807 1808 public void dispatchCreate() { 1809 mStateSaved = false; 1810 moveToState(Fragment.CREATED, false); 1811 } 1812 1813 public void dispatchActivityCreated() { 1814 mStateSaved = false; 1815 moveToState(Fragment.ACTIVITY_CREATED, false); 1816 } 1817 1818 public void dispatchStart() { 1819 mStateSaved = false; 1820 moveToState(Fragment.STARTED, false); 1821 } 1822 1823 public void dispatchResume() { 1824 mStateSaved = false; 1825 moveToState(Fragment.RESUMED, false); 1826 } 1827 1828 public void dispatchPause() { 1829 moveToState(Fragment.STARTED, false); 1830 } 1831 1832 public void dispatchStop() { 1833 // See saveAllState() for the explanation of this. We do this for 1834 // all platform versions, to keep our behavior more consistent between 1835 // them. 1836 mStateSaved = true; 1837 1838 moveToState(Fragment.STOPPED, false); 1839 } 1840 1841 public void dispatchReallyStop() { 1842 moveToState(Fragment.ACTIVITY_CREATED, false); 1843 } 1844 1845 public void dispatchDestroy() { 1846 mDestroyed = true; 1847 execPendingActions(); 1848 moveToState(Fragment.INITIALIZING, false); 1849 mActivity = null; 1850 } 1851 1852 public void dispatchConfigurationChanged(Configuration newConfig) { 1853 if (mActive != null) { 1854 for (int i=0; i<mAdded.size(); i++) { 1855 Fragment f = mAdded.get(i); 1856 if (f != null) { 1857 f.onConfigurationChanged(newConfig); 1858 } 1859 } 1860 } 1861 } 1862 1863 public void dispatchLowMemory() { 1864 if (mActive != null) { 1865 for (int i=0; i<mAdded.size(); i++) { 1866 Fragment f = mAdded.get(i); 1867 if (f != null) { 1868 f.onLowMemory(); 1869 } 1870 } 1871 } 1872 } 1873 1874 public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) { 1875 boolean show = false; 1876 ArrayList<Fragment> newMenus = null; 1877 if (mActive != null) { 1878 for (int i=0; i<mAdded.size(); i++) { 1879 Fragment f = mAdded.get(i); 1880 if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) { 1881 show = true; 1882 f.onCreateOptionsMenu(menu, inflater); 1883 if (newMenus == null) { 1884 newMenus = new ArrayList<Fragment>(); 1885 } 1886 newMenus.add(f); 1887 } 1888 } 1889 } 1890 1891 if (mCreatedMenus != null) { 1892 for (int i=0; i<mCreatedMenus.size(); i++) { 1893 Fragment f = mCreatedMenus.get(i); 1894 if (newMenus == null || !newMenus.contains(f)) { 1895 f.onDestroyOptionsMenu(); 1896 } 1897 } 1898 } 1899 1900 mCreatedMenus = newMenus; 1901 1902 return show; 1903 } 1904 1905 public boolean dispatchPrepareOptionsMenu(Menu menu) { 1906 boolean show = false; 1907 if (mActive != null) { 1908 for (int i=0; i<mAdded.size(); i++) { 1909 Fragment f = mAdded.get(i); 1910 if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) { 1911 show = true; 1912 f.onPrepareOptionsMenu(menu); 1913 } 1914 } 1915 } 1916 return show; 1917 } 1918 1919 public boolean dispatchOptionsItemSelected(MenuItem item) { 1920 if (mActive != null) { 1921 for (int i=0; i<mAdded.size(); i++) { 1922 Fragment f = mAdded.get(i); 1923 if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) { 1924 if (f.onOptionsItemSelected(item)) { 1925 return true; 1926 } 1927 } 1928 } 1929 } 1930 return false; 1931 } 1932 1933 public boolean dispatchContextItemSelected(MenuItem item) { 1934 if (mActive != null) { 1935 for (int i=0; i<mAdded.size(); i++) { 1936 Fragment f = mAdded.get(i); 1937 if (f != null && !f.mHidden && f.mUserVisibleHint) { 1938 if (f.onContextItemSelected(item)) { 1939 return true; 1940 } 1941 } 1942 } 1943 } 1944 return false; 1945 } 1946 1947 public void dispatchOptionsMenuClosed(Menu menu) { 1948 if (mActive != null) { 1949 for (int i=0; i<mAdded.size(); i++) { 1950 Fragment f = mAdded.get(i); 1951 if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible) { 1952 f.onOptionsMenuClosed(menu); 1953 } 1954 } 1955 } 1956 } 1957 1958 public static int reverseTransit(int transit) { 1959 int rev = 0; 1960 switch (transit) { 1961 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 1962 rev = FragmentTransaction.TRANSIT_FRAGMENT_CLOSE; 1963 break; 1964 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 1965 rev = FragmentTransaction.TRANSIT_FRAGMENT_OPEN; 1966 break; 1967 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 1968 rev = FragmentTransaction.TRANSIT_FRAGMENT_FADE; 1969 break; 1970 } 1971 return rev; 1972 1973 } 1974 1975 public static final int ANIM_STYLE_OPEN_ENTER = 1; 1976 public static final int ANIM_STYLE_OPEN_EXIT = 2; 1977 public static final int ANIM_STYLE_CLOSE_ENTER = 3; 1978 public static final int ANIM_STYLE_CLOSE_EXIT = 4; 1979 public static final int ANIM_STYLE_FADE_ENTER = 5; 1980 public static final int ANIM_STYLE_FADE_EXIT = 6; 1981 1982 public static int transitToStyleIndex(int transit, boolean enter) { 1983 int animAttr = -1; 1984 switch (transit) { 1985 case FragmentTransaction.TRANSIT_FRAGMENT_OPEN: 1986 animAttr = enter ? ANIM_STYLE_OPEN_ENTER : ANIM_STYLE_OPEN_EXIT; 1987 break; 1988 case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE: 1989 animAttr = enter ? ANIM_STYLE_CLOSE_ENTER : ANIM_STYLE_CLOSE_EXIT; 1990 break; 1991 case FragmentTransaction.TRANSIT_FRAGMENT_FADE: 1992 animAttr = enter ? ANIM_STYLE_FADE_ENTER : ANIM_STYLE_FADE_EXIT; 1993 break; 1994 } 1995 return animAttr; 1996 } 1997} 1998