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