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