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