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