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 static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP; 20 21import android.animation.Animator; 22import android.app.Activity; 23import android.content.ComponentCallbacks; 24import android.content.Context; 25import android.content.Intent; 26import android.content.IntentSender; 27import android.content.res.Configuration; 28import android.content.res.Resources; 29import android.os.Bundle; 30import android.os.Looper; 31import android.os.Parcel; 32import android.os.Parcelable; 33import android.support.annotation.CallSuper; 34import android.support.annotation.NonNull; 35import android.support.annotation.Nullable; 36import android.support.annotation.RestrictTo; 37import android.support.annotation.StringRes; 38import android.support.v4.util.DebugUtils; 39import android.support.v4.util.SimpleArrayMap; 40import android.support.v4.view.LayoutInflaterCompat; 41import android.util.AttributeSet; 42import android.util.Log; 43import android.util.SparseArray; 44import android.view.ContextMenu; 45import android.view.ContextMenu.ContextMenuInfo; 46import android.view.LayoutInflater; 47import android.view.Menu; 48import android.view.MenuInflater; 49import android.view.MenuItem; 50import android.view.View; 51import android.view.View.OnCreateContextMenuListener; 52import android.view.ViewGroup; 53import android.view.animation.Animation; 54import android.widget.AdapterView; 55 56import java.io.FileDescriptor; 57import java.io.PrintWriter; 58import java.lang.reflect.InvocationTargetException; 59 60final class FragmentState implements Parcelable { 61 final String mClassName; 62 final int mIndex; 63 final boolean mFromLayout; 64 final int mFragmentId; 65 final int mContainerId; 66 final String mTag; 67 final boolean mRetainInstance; 68 final boolean mDetached; 69 final Bundle mArguments; 70 final boolean mHidden; 71 72 Bundle mSavedFragmentState; 73 74 Fragment mInstance; 75 76 public FragmentState(Fragment frag) { 77 mClassName = frag.getClass().getName(); 78 mIndex = frag.mIndex; 79 mFromLayout = frag.mFromLayout; 80 mFragmentId = frag.mFragmentId; 81 mContainerId = frag.mContainerId; 82 mTag = frag.mTag; 83 mRetainInstance = frag.mRetainInstance; 84 mDetached = frag.mDetached; 85 mArguments = frag.mArguments; 86 mHidden = frag.mHidden; 87 } 88 89 public FragmentState(Parcel in) { 90 mClassName = in.readString(); 91 mIndex = in.readInt(); 92 mFromLayout = in.readInt() != 0; 93 mFragmentId = in.readInt(); 94 mContainerId = in.readInt(); 95 mTag = in.readString(); 96 mRetainInstance = in.readInt() != 0; 97 mDetached = in.readInt() != 0; 98 mArguments = in.readBundle(); 99 mHidden = in.readInt() != 0; 100 mSavedFragmentState = in.readBundle(); 101 } 102 103 public Fragment instantiate(FragmentHostCallback host, FragmentContainer container, 104 Fragment parent, FragmentManagerNonConfig childNonConfig) { 105 if (mInstance == null) { 106 final Context context = host.getContext(); 107 if (mArguments != null) { 108 mArguments.setClassLoader(context.getClassLoader()); 109 } 110 111 if (container != null) { 112 mInstance = container.instantiate(context, mClassName, mArguments); 113 } else { 114 mInstance = Fragment.instantiate(context, mClassName, mArguments); 115 } 116 117 if (mSavedFragmentState != null) { 118 mSavedFragmentState.setClassLoader(context.getClassLoader()); 119 mInstance.mSavedFragmentState = mSavedFragmentState; 120 } 121 mInstance.setIndex(mIndex, parent); 122 mInstance.mFromLayout = mFromLayout; 123 mInstance.mRestored = true; 124 mInstance.mFragmentId = mFragmentId; 125 mInstance.mContainerId = mContainerId; 126 mInstance.mTag = mTag; 127 mInstance.mRetainInstance = mRetainInstance; 128 mInstance.mDetached = mDetached; 129 mInstance.mHidden = mHidden; 130 mInstance.mFragmentManager = host.mFragmentManager; 131 132 if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG, 133 "Instantiated fragment " + mInstance); 134 } 135 mInstance.mChildNonConfig = childNonConfig; 136 return mInstance; 137 } 138 139 @Override 140 public int describeContents() { 141 return 0; 142 } 143 144 @Override 145 public void writeToParcel(Parcel dest, int flags) { 146 dest.writeString(mClassName); 147 dest.writeInt(mIndex); 148 dest.writeInt(mFromLayout ? 1 : 0); 149 dest.writeInt(mFragmentId); 150 dest.writeInt(mContainerId); 151 dest.writeString(mTag); 152 dest.writeInt(mRetainInstance ? 1 : 0); 153 dest.writeInt(mDetached ? 1 : 0); 154 dest.writeBundle(mArguments); 155 dest.writeInt(mHidden? 1 : 0); 156 dest.writeBundle(mSavedFragmentState); 157 } 158 159 public static final Parcelable.Creator<FragmentState> CREATOR 160 = new Parcelable.Creator<FragmentState>() { 161 @Override 162 public FragmentState createFromParcel(Parcel in) { 163 return new FragmentState(in); 164 } 165 166 @Override 167 public FragmentState[] newArray(int size) { 168 return new FragmentState[size]; 169 } 170 }; 171} 172 173/** 174 * Static library support version of the framework's {@link android.app.Fragment}. 175 * Used to write apps that run on platforms prior to Android 3.0. When running 176 * on Android 3.0 or above, this implementation is still used; it does not try 177 * to switch to the framework's implementation. See the framework {@link android.app.Fragment} 178 * documentation for a class overview. 179 * 180 * <p>The main differences when using this support version instead of the framework version are: 181 * <ul> 182 * <li>Your activity must extend {@link FragmentActivity} 183 * <li>You must call {@link FragmentActivity#getSupportFragmentManager} to get the 184 * {@link FragmentManager} 185 * </ul> 186 * 187 */ 188public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener { 189 private static final SimpleArrayMap<String, Class<?>> sClassMap = 190 new SimpleArrayMap<String, Class<?>>(); 191 192 static final Object USE_DEFAULT_TRANSITION = new Object(); 193 194 static final int INITIALIZING = 0; // Not yet created. 195 static final int CREATED = 1; // Created. 196 static final int ACTIVITY_CREATED = 2; // The activity has finished its creation. 197 static final int STOPPED = 3; // Fully created, not started. 198 static final int STARTED = 4; // Created and started, not resumed. 199 static final int RESUMED = 5; // Created started and resumed. 200 201 int mState = INITIALIZING; 202 203 // When instantiated from saved state, this is the saved state. 204 Bundle mSavedFragmentState; 205 SparseArray<Parcelable> mSavedViewState; 206 207 // Index into active fragment array. 208 int mIndex = -1; 209 210 // Internal unique name for this fragment; 211 String mWho; 212 213 // Construction arguments; 214 Bundle mArguments; 215 216 // Target fragment. 217 Fragment mTarget; 218 219 // For use when retaining a fragment: this is the index of the last mTarget. 220 int mTargetIndex = -1; 221 222 // Target request code. 223 int mTargetRequestCode; 224 225 // True if the fragment is in the list of added fragments. 226 boolean mAdded; 227 228 // If set this fragment is being removed from its activity. 229 boolean mRemoving; 230 231 // Set to true if this fragment was instantiated from a layout file. 232 boolean mFromLayout; 233 234 // Set to true when the view has actually been inflated in its layout. 235 boolean mInLayout; 236 237 // True if this fragment has been restored from previously saved state. 238 boolean mRestored; 239 240 // True if performCreateView has been called and a matching call to performDestroyView 241 // has not yet happened. 242 boolean mPerformedCreateView; 243 244 // Number of active back stack entries this fragment is in. 245 int mBackStackNesting; 246 247 // The fragment manager we are associated with. Set as soon as the 248 // fragment is used in a transaction; cleared after it has been removed 249 // from all transactions. 250 FragmentManagerImpl mFragmentManager; 251 252 // Host this fragment is attached to. 253 FragmentHostCallback mHost; 254 255 // Private fragment manager for child fragments inside of this one. 256 FragmentManagerImpl mChildFragmentManager; 257 258 // For use when restoring fragment state and descendant fragments are retained. 259 // This state is set by FragmentState.instantiate and cleared in onCreate. 260 FragmentManagerNonConfig mChildNonConfig; 261 262 // If this Fragment is contained in another Fragment, this is that container. 263 Fragment mParentFragment; 264 265 // The optional identifier for this fragment -- either the container ID if it 266 // was dynamically added to the view hierarchy, or the ID supplied in 267 // layout. 268 int mFragmentId; 269 270 // When a fragment is being dynamically added to the view hierarchy, this 271 // is the identifier of the parent container it is being added to. 272 int mContainerId; 273 274 // The optional named tag for this fragment -- usually used to find 275 // fragments that are not part of the layout. 276 String mTag; 277 278 // Set to true when the app has requested that this fragment be hidden 279 // from the user. 280 boolean mHidden; 281 282 // Set to true when the app has requested that this fragment be deactivated. 283 boolean mDetached; 284 285 // If set this fragment would like its instance retained across 286 // configuration changes. 287 boolean mRetainInstance; 288 289 // If set this fragment is being retained across the current config change. 290 boolean mRetaining; 291 292 // If set this fragment has menu items to contribute. 293 boolean mHasMenu; 294 295 // Set to true to allow the fragment's menu to be shown. 296 boolean mMenuVisible = true; 297 298 // Used to verify that subclasses call through to super class. 299 boolean mCalled; 300 301 // The parent container of the fragment after dynamically added to UI. 302 ViewGroup mContainer; 303 304 // The View generated for this fragment. 305 View mView; 306 307 // The real inner view that will save/restore state. 308 View mInnerView; 309 310 // Whether this fragment should defer starting until after other fragments 311 // have been started and their loaders are finished. 312 boolean mDeferStart; 313 314 // Hint provided by the app that this fragment is currently visible to the user. 315 boolean mUserVisibleHint = true; 316 317 LoaderManagerImpl mLoaderManager; 318 boolean mLoadersStarted; 319 boolean mCheckedForLoaderManager; 320 321 // The animation and transition information for the fragment. This will be null 322 // unless the elements are explicitly accessed and should remain null for Fragments 323 // without Views. 324 AnimationInfo mAnimationInfo; 325 326 // True if the View was added, and its animation has yet to be run. This could 327 // also indicate that the fragment view hasn't been made visible, even if there is no 328 // animation for this fragment. 329 boolean mIsNewlyAdded; 330 331 // True if mHidden has been changed and the animation should be scheduled. 332 boolean mHiddenChanged; 333 334 // The alpha of the view when the view was added and then postponed. If the value is less 335 // than zero, this means that the view's add was canceled and should not participate in 336 // removal animations. 337 float mPostponedAlpha; 338 339 // The cached value from onGetLayoutInflater(Bundle) that will be returned from 340 // getLayoutInflater() 341 LayoutInflater mLayoutInflater; 342 343 /** 344 * State information that has been retrieved from a fragment instance 345 * through {@link FragmentManager#saveFragmentInstanceState(Fragment) 346 * FragmentManager.saveFragmentInstanceState}. 347 */ 348 public static class SavedState implements Parcelable { 349 final Bundle mState; 350 351 SavedState(Bundle state) { 352 mState = state; 353 } 354 355 SavedState(Parcel in, ClassLoader loader) { 356 mState = in.readBundle(); 357 if (loader != null && mState != null) { 358 mState.setClassLoader(loader); 359 } 360 } 361 362 @Override 363 public int describeContents() { 364 return 0; 365 } 366 367 @Override 368 public void writeToParcel(Parcel dest, int flags) { 369 dest.writeBundle(mState); 370 } 371 372 public static final Parcelable.Creator<SavedState> CREATOR 373 = new Parcelable.Creator<SavedState>() { 374 @Override 375 public SavedState createFromParcel(Parcel in) { 376 return new SavedState(in, null); 377 } 378 379 @Override 380 public SavedState[] newArray(int size) { 381 return new SavedState[size]; 382 } 383 }; 384 } 385 386 /** 387 * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when 388 * there is an instantiation failure. 389 */ 390 static public class InstantiationException extends RuntimeException { 391 public InstantiationException(String msg, Exception cause) { 392 super(msg, cause); 393 } 394 } 395 396 /** 397 * Default constructor. <strong>Every</strong> fragment must have an 398 * empty constructor, so it can be instantiated when restoring its 399 * activity's state. It is strongly recommended that subclasses do not 400 * have other constructors with parameters, since these constructors 401 * will not be called when the fragment is re-instantiated; instead, 402 * arguments can be supplied by the caller with {@link #setArguments} 403 * and later retrieved by the Fragment with {@link #getArguments}. 404 * 405 * <p>Applications should generally not implement a constructor. Prefer 406 * {@link #onAttach(Context)} instead. It is the first place application code can run where 407 * the fragment is ready to be used - the point where the fragment is actually associated with 408 * its context. Some applications may also want to implement {@link #onInflate} to retrieve 409 * attributes from a layout resource, although note this happens when the fragment is attached. 410 */ 411 public Fragment() { 412 } 413 414 /** 415 * Like {@link #instantiate(Context, String, Bundle)} but with a null 416 * argument Bundle. 417 */ 418 public static Fragment instantiate(Context context, String fname) { 419 return instantiate(context, fname, null); 420 } 421 422 /** 423 * Create a new instance of a Fragment with the given class name. This is 424 * the same as calling its empty constructor. 425 * 426 * @param context The calling context being used to instantiate the fragment. 427 * This is currently just used to get its ClassLoader. 428 * @param fname The class name of the fragment to instantiate. 429 * @param args Bundle of arguments to supply to the fragment, which it 430 * can retrieve with {@link #getArguments()}. May be null. 431 * @return Returns a new fragment instance. 432 * @throws InstantiationException If there is a failure in instantiating 433 * the given fragment class. This is a runtime exception; it is not 434 * normally expected to happen. 435 */ 436 public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) { 437 try { 438 Class<?> clazz = sClassMap.get(fname); 439 if (clazz == null) { 440 // Class not found in the cache, see if it's real, and try to add it 441 clazz = context.getClassLoader().loadClass(fname); 442 sClassMap.put(fname, clazz); 443 } 444 Fragment f = (Fragment) clazz.getConstructor().newInstance(); 445 if (args != null) { 446 args.setClassLoader(f.getClass().getClassLoader()); 447 f.setArguments(args); 448 } 449 return f; 450 } catch (ClassNotFoundException e) { 451 throw new InstantiationException("Unable to instantiate fragment " + fname 452 + ": make sure class name exists, is public, and has an" 453 + " empty constructor that is public", e); 454 } catch (java.lang.InstantiationException e) { 455 throw new InstantiationException("Unable to instantiate fragment " + fname 456 + ": make sure class name exists, is public, and has an" 457 + " empty constructor that is public", e); 458 } catch (IllegalAccessException e) { 459 throw new InstantiationException("Unable to instantiate fragment " + fname 460 + ": make sure class name exists, is public, and has an" 461 + " empty constructor that is public", e); 462 } catch (NoSuchMethodException e) { 463 throw new InstantiationException("Unable to instantiate fragment " + fname 464 + ": could not find Fragment constructor", e); 465 } catch (InvocationTargetException e) { 466 throw new InstantiationException("Unable to instantiate fragment " + fname 467 + ": calling Fragment constructor caused an exception", e); 468 } 469 } 470 471 /** 472 * Determine if the given fragment name is a support library fragment class. 473 * 474 * @param context Context used to determine the correct ClassLoader to use 475 * @param fname Class name of the fragment to test 476 * @return true if <code>fname</code> is <code>android.support.v4.app.Fragment</code> 477 * or a subclass, false otherwise. 478 */ 479 static boolean isSupportFragmentClass(Context context, String fname) { 480 try { 481 Class<?> clazz = sClassMap.get(fname); 482 if (clazz == null) { 483 // Class not found in the cache, see if it's real, and try to add it 484 clazz = context.getClassLoader().loadClass(fname); 485 sClassMap.put(fname, clazz); 486 } 487 return Fragment.class.isAssignableFrom(clazz); 488 } catch (ClassNotFoundException e) { 489 return false; 490 } 491 } 492 493 final void restoreViewState(Bundle savedInstanceState) { 494 if (mSavedViewState != null) { 495 mInnerView.restoreHierarchyState(mSavedViewState); 496 mSavedViewState = null; 497 } 498 mCalled = false; 499 onViewStateRestored(savedInstanceState); 500 if (!mCalled) { 501 throw new SuperNotCalledException("Fragment " + this 502 + " did not call through to super.onViewStateRestored()"); 503 } 504 } 505 506 final void setIndex(int index, Fragment parent) { 507 mIndex = index; 508 if (parent != null) { 509 mWho = parent.mWho + ":" + mIndex; 510 } else { 511 mWho = "android:fragment:" + mIndex; 512 } 513 } 514 515 final boolean isInBackStack() { 516 return mBackStackNesting > 0; 517 } 518 519 /** 520 * Subclasses can not override equals(). 521 */ 522 @Override final public boolean equals(Object o) { 523 return super.equals(o); 524 } 525 526 /** 527 * Subclasses can not override hashCode(). 528 */ 529 @Override final public int hashCode() { 530 return super.hashCode(); 531 } 532 533 @Override 534 public String toString() { 535 StringBuilder sb = new StringBuilder(128); 536 DebugUtils.buildShortClassTag(this, sb); 537 if (mIndex >= 0) { 538 sb.append(" #"); 539 sb.append(mIndex); 540 } 541 if (mFragmentId != 0) { 542 sb.append(" id=0x"); 543 sb.append(Integer.toHexString(mFragmentId)); 544 } 545 if (mTag != null) { 546 sb.append(" "); 547 sb.append(mTag); 548 } 549 sb.append('}'); 550 return sb.toString(); 551 } 552 553 /** 554 * Return the identifier this fragment is known by. This is either 555 * the android:id value supplied in a layout or the container view ID 556 * supplied when adding the fragment. 557 */ 558 final public int getId() { 559 return mFragmentId; 560 } 561 562 /** 563 * Get the tag name of the fragment, if specified. 564 */ 565 final public String getTag() { 566 return mTag; 567 } 568 569 /** 570 * Supply the construction arguments for this fragment. 571 * The arguments supplied here will be retained across fragment destroy and 572 * creation. 573 * <p>This method cannot be called if the fragment is added to a FragmentManager and 574 * if {@link #isStateSaved()} would return true.</p> 575 */ 576 public void setArguments(Bundle args) { 577 if (mIndex >= 0 && isStateSaved()) { 578 throw new IllegalStateException("Fragment already active and state has been saved"); 579 } 580 mArguments = args; 581 } 582 583 /** 584 * Return the arguments supplied when the fragment was instantiated, 585 * if any. 586 */ 587 final public Bundle getArguments() { 588 return mArguments; 589 } 590 591 /** 592 * Returns true if this fragment is added and its state has already been saved 593 * by its host. Any operations that would change saved state should not be performed 594 * if this method returns true, and some operations such as {@link #setArguments(Bundle)} 595 * will fail. 596 * 597 * @return true if this fragment's state has already been saved by its host 598 */ 599 public final boolean isStateSaved() { 600 if (mFragmentManager == null) { 601 return false; 602 } 603 return mFragmentManager.isStateSaved(); 604 } 605 606 /** 607 * Set the initial saved state that this Fragment should restore itself 608 * from when first being constructed, as returned by 609 * {@link FragmentManager#saveFragmentInstanceState(Fragment) 610 * FragmentManager.saveFragmentInstanceState}. 611 * 612 * @param state The state the fragment should be restored from. 613 */ 614 public void setInitialSavedState(SavedState state) { 615 if (mIndex >= 0) { 616 throw new IllegalStateException("Fragment already active"); 617 } 618 mSavedFragmentState = state != null && state.mState != null 619 ? state.mState : null; 620 } 621 622 /** 623 * Optional target for this fragment. This may be used, for example, 624 * if this fragment is being started by another, and when done wants to 625 * give a result back to the first. The target set here is retained 626 * across instances via {@link FragmentManager#putFragment 627 * FragmentManager.putFragment()}. 628 * 629 * @param fragment The fragment that is the target of this one. 630 * @param requestCode Optional request code, for convenience if you 631 * are going to call back with {@link #onActivityResult(int, int, Intent)}. 632 */ 633 @SuppressWarnings("ReferenceEquality") 634 public void setTargetFragment(Fragment fragment, int requestCode) { 635 // Don't allow a caller to set a target fragment in another FragmentManager, 636 // but there's a snag: people do set target fragments before fragments get added. 637 // We'll have the FragmentManager check that for validity when we move 638 // the fragments to a valid state. 639 final FragmentManager mine = getFragmentManager(); 640 final FragmentManager theirs = fragment != null ? fragment.getFragmentManager() : null; 641 if (mine != null && theirs != null && mine != theirs) { 642 throw new IllegalArgumentException("Fragment " + fragment 643 + " must share the same FragmentManager to be set as a target fragment"); 644 } 645 646 // Don't let someone create a cycle. 647 for (Fragment check = fragment; check != null; check = check.getTargetFragment()) { 648 if (check == this) { 649 throw new IllegalArgumentException("Setting " + fragment + " as the target of " 650 + this + " would create a target cycle"); 651 } 652 } 653 mTarget = fragment; 654 mTargetRequestCode = requestCode; 655 } 656 657 /** 658 * Return the target fragment set by {@link #setTargetFragment}. 659 */ 660 final public Fragment getTargetFragment() { 661 return mTarget; 662 } 663 664 /** 665 * Return the target request code set by {@link #setTargetFragment}. 666 */ 667 final public int getTargetRequestCode() { 668 return mTargetRequestCode; 669 } 670 671 /** 672 * Return the {@link Context} this fragment is currently associated with. 673 */ 674 public Context getContext() { 675 return mHost == null ? null : mHost.getContext(); 676 } 677 678 /** 679 * Return the {@link FragmentActivity} this fragment is currently associated with. 680 * May return {@code null} if the fragment is associated with a {@link Context} 681 * instead. 682 */ 683 final public FragmentActivity getActivity() { 684 return mHost == null ? null : (FragmentActivity) mHost.getActivity(); 685 } 686 687 /** 688 * Return the host object of this fragment. May return {@code null} if the fragment 689 * isn't currently being hosted. 690 */ 691 final public Object getHost() { 692 return mHost == null ? null : mHost.onGetHost(); 693 } 694 695 /** 696 * Return <code>getActivity().getResources()</code>. 697 */ 698 final public Resources getResources() { 699 if (mHost == null) { 700 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 701 } 702 return mHost.getContext().getResources(); 703 } 704 705 /** 706 * Return a localized, styled CharSequence from the application's package's 707 * default string table. 708 * 709 * @param resId Resource id for the CharSequence text 710 */ 711 public final CharSequence getText(@StringRes int resId) { 712 return getResources().getText(resId); 713 } 714 715 /** 716 * Return a localized string from the application's package's 717 * default string table. 718 * 719 * @param resId Resource id for the string 720 */ 721 public final String getString(@StringRes int resId) { 722 return getResources().getString(resId); 723 } 724 725 /** 726 * Return a localized formatted string from the application's package's 727 * default string table, substituting the format arguments as defined in 728 * {@link java.util.Formatter} and {@link java.lang.String#format}. 729 * 730 * @param resId Resource id for the format string 731 * @param formatArgs The format arguments that will be used for substitution. 732 */ 733 734 public final String getString(@StringRes int resId, Object... formatArgs) { 735 return getResources().getString(resId, formatArgs); 736 } 737 738 /** 739 * Return the FragmentManager for interacting with fragments associated 740 * with this fragment's activity. Note that this will be non-null slightly 741 * before {@link #getActivity()}, during the time from when the fragment is 742 * placed in a {@link FragmentTransaction} until it is committed and 743 * attached to its activity. 744 * 745 * <p>If this Fragment is a child of another Fragment, the FragmentManager 746 * returned here will be the parent's {@link #getChildFragmentManager()}. 747 */ 748 final public FragmentManager getFragmentManager() { 749 return mFragmentManager; 750 } 751 752 /** 753 * Return a private FragmentManager for placing and managing Fragments 754 * inside of this Fragment. 755 */ 756 final public FragmentManager getChildFragmentManager() { 757 if (mChildFragmentManager == null) { 758 instantiateChildFragmentManager(); 759 if (mState >= RESUMED) { 760 mChildFragmentManager.dispatchResume(); 761 } else if (mState >= STARTED) { 762 mChildFragmentManager.dispatchStart(); 763 } else if (mState >= ACTIVITY_CREATED) { 764 mChildFragmentManager.dispatchActivityCreated(); 765 } else if (mState >= CREATED) { 766 mChildFragmentManager.dispatchCreate(); 767 } 768 } 769 return mChildFragmentManager; 770 } 771 772 /** 773 * Return this fragment's child FragmentManager one has been previously created, 774 * otherwise null. 775 */ 776 FragmentManager peekChildFragmentManager() { 777 return mChildFragmentManager; 778 } 779 780 /** 781 * Returns the parent Fragment containing this Fragment. If this Fragment 782 * is attached directly to an Activity, returns null. 783 */ 784 final public Fragment getParentFragment() { 785 return mParentFragment; 786 } 787 788 /** 789 * Return true if the fragment is currently added to its activity. 790 */ 791 final public boolean isAdded() { 792 return mHost != null && mAdded; 793 } 794 795 /** 796 * Return true if the fragment has been explicitly detached from the UI. 797 * That is, {@link FragmentTransaction#detach(Fragment) 798 * FragmentTransaction.detach(Fragment)} has been used on it. 799 */ 800 final public boolean isDetached() { 801 return mDetached; 802 } 803 804 /** 805 * Return true if this fragment is currently being removed from its 806 * activity. This is <em>not</em> whether its activity is finishing, but 807 * rather whether it is in the process of being removed from its activity. 808 */ 809 final public boolean isRemoving() { 810 return mRemoving; 811 } 812 813 /** 814 * Return true if the layout is included as part of an activity view 815 * hierarchy via the <fragment> tag. This will always be true when 816 * fragments are created through the <fragment> tag, <em>except</em> 817 * in the case where an old fragment is restored from a previous state and 818 * it does not appear in the layout of the current state. 819 */ 820 final public boolean isInLayout() { 821 return mInLayout; 822 } 823 824 /** 825 * Return true if the fragment is in the resumed state. This is true 826 * for the duration of {@link #onResume()} and {@link #onPause()} as well. 827 */ 828 final public boolean isResumed() { 829 return mState >= RESUMED; 830 } 831 832 /** 833 * Return true if the fragment is currently visible to the user. This means 834 * it: (1) has been added, (2) has its view attached to the window, and 835 * (3) is not hidden. 836 */ 837 final public boolean isVisible() { 838 return isAdded() && !isHidden() && mView != null 839 && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE; 840 } 841 842 /** 843 * Return true if the fragment has been hidden. By default fragments 844 * are shown. You can find out about changes to this state with 845 * {@link #onHiddenChanged}. Note that the hidden state is orthogonal 846 * to other states -- that is, to be visible to the user, a fragment 847 * must be both started and not hidden. 848 */ 849 final public boolean isHidden() { 850 return mHidden; 851 } 852 853 /** @hide */ 854 @RestrictTo(LIBRARY_GROUP) 855 final public boolean hasOptionsMenu() { 856 return mHasMenu; 857 } 858 859 /** @hide */ 860 @RestrictTo(LIBRARY_GROUP) 861 final public boolean isMenuVisible() { 862 return mMenuVisible; 863 } 864 865 /** 866 * Called when the hidden state (as returned by {@link #isHidden()} of 867 * the fragment has changed. Fragments start out not hidden; this will 868 * be called whenever the fragment changes state from that. 869 * @param hidden True if the fragment is now hidden, false otherwise. 870 */ 871 public void onHiddenChanged(boolean hidden) { 872 } 873 874 /** 875 * Control whether a fragment instance is retained across Activity 876 * re-creation (such as from a configuration change). This can only 877 * be used with fragments not in the back stack. If set, the fragment 878 * lifecycle will be slightly different when an activity is recreated: 879 * <ul> 880 * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still 881 * will be, because the fragment is being detached from its current activity). 882 * <li> {@link #onCreate(Bundle)} will not be called since the fragment 883 * is not being re-created. 884 * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b> 885 * still be called. 886 * </ul> 887 */ 888 public void setRetainInstance(boolean retain) { 889 mRetainInstance = retain; 890 } 891 892 final public boolean getRetainInstance() { 893 return mRetainInstance; 894 } 895 896 /** 897 * Report that this fragment would like to participate in populating 898 * the options menu by receiving a call to {@link #onCreateOptionsMenu} 899 * and related methods. 900 * 901 * @param hasMenu If true, the fragment has menu items to contribute. 902 */ 903 public void setHasOptionsMenu(boolean hasMenu) { 904 if (mHasMenu != hasMenu) { 905 mHasMenu = hasMenu; 906 if (isAdded() && !isHidden()) { 907 mHost.onSupportInvalidateOptionsMenu(); 908 } 909 } 910 } 911 912 /** 913 * Set a hint for whether this fragment's menu should be visible. This 914 * is useful if you know that a fragment has been placed in your view 915 * hierarchy so that the user can not currently seen it, so any menu items 916 * it has should also not be shown. 917 * 918 * @param menuVisible The default is true, meaning the fragment's menu will 919 * be shown as usual. If false, the user will not see the menu. 920 */ 921 public void setMenuVisibility(boolean menuVisible) { 922 if (mMenuVisible != menuVisible) { 923 mMenuVisible = menuVisible; 924 if (mHasMenu && isAdded() && !isHidden()) { 925 mHost.onSupportInvalidateOptionsMenu(); 926 } 927 } 928 } 929 930 /** 931 * Set a hint to the system about whether this fragment's UI is currently visible 932 * to the user. This hint defaults to true and is persistent across fragment instance 933 * state save and restore. 934 * 935 * <p>An app may set this to false to indicate that the fragment's UI is 936 * scrolled out of visibility or is otherwise not directly visible to the user. 937 * This may be used by the system to prioritize operations such as fragment lifecycle updates 938 * or loader ordering behavior.</p> 939 * 940 * <p><strong>Note:</strong> This method may be called outside of the fragment lifecycle. 941 * and thus has no ordering guarantees with regard to fragment lifecycle method calls.</p> 942 * 943 * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default), 944 * false if it is not. 945 */ 946 public void setUserVisibleHint(boolean isVisibleToUser) { 947 if (!mUserVisibleHint && isVisibleToUser && mState < STARTED 948 && mFragmentManager != null && isAdded()) { 949 mFragmentManager.performPendingDeferredStart(this); 950 } 951 mUserVisibleHint = isVisibleToUser; 952 mDeferStart = mState < STARTED && !isVisibleToUser; 953 } 954 955 /** 956 * @return The current value of the user-visible hint on this fragment. 957 * @see #setUserVisibleHint(boolean) 958 */ 959 public boolean getUserVisibleHint() { 960 return mUserVisibleHint; 961 } 962 963 /** 964 * Return the LoaderManager for this fragment, creating it if needed. 965 */ 966 public LoaderManager getLoaderManager() { 967 if (mLoaderManager != null) { 968 return mLoaderManager; 969 } 970 if (mHost == null) { 971 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 972 } 973 mCheckedForLoaderManager = true; 974 mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, true); 975 return mLoaderManager; 976 } 977 978 /** 979 * Call {@link Activity#startActivity(Intent)} from the fragment's 980 * containing Activity. 981 */ 982 public void startActivity(Intent intent) { 983 startActivity(intent, null); 984 } 985 986 /** 987 * Call {@link Activity#startActivity(Intent, Bundle)} from the fragment's 988 * containing Activity. 989 */ 990 public void startActivity(Intent intent, @Nullable Bundle options) { 991 if (mHost == null) { 992 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 993 } 994 mHost.onStartActivityFromFragment(this /*fragment*/, intent, -1, options); 995 } 996 997 /** 998 * Call {@link Activity#startActivityForResult(Intent, int)} from the fragment's 999 * containing Activity. 1000 */ 1001 public void startActivityForResult(Intent intent, int requestCode) { 1002 startActivityForResult(intent, requestCode, null); 1003 } 1004 1005 /** 1006 * Call {@link Activity#startActivityForResult(Intent, int, Bundle)} from the fragment's 1007 * containing Activity. 1008 */ 1009 public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) { 1010 if (mHost == null) { 1011 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 1012 } 1013 mHost.onStartActivityFromFragment(this /*fragment*/, intent, requestCode, options); 1014 } 1015 1016 /** 1017 * Call {@link Activity#startIntentSenderForResult(IntentSender, int, Intent, int, int, int, 1018 * Bundle)} from the fragment's containing Activity. 1019 */ 1020 public void startIntentSenderForResult(IntentSender intent, int requestCode, 1021 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, 1022 Bundle options) throws IntentSender.SendIntentException { 1023 if (mHost == null) { 1024 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 1025 } 1026 mHost.onStartIntentSenderFromFragment(this, intent, requestCode, fillInIntent, flagsMask, 1027 flagsValues, extraFlags, options); 1028 } 1029 1030 /** 1031 * Receive the result from a previous call to 1032 * {@link #startActivityForResult(Intent, int)}. This follows the 1033 * related Activity API as described there in 1034 * {@link Activity#onActivityResult(int, int, Intent)}. 1035 * 1036 * @param requestCode The integer request code originally supplied to 1037 * startActivityForResult(), allowing you to identify who this 1038 * result came from. 1039 * @param resultCode The integer result code returned by the child activity 1040 * through its setResult(). 1041 * @param data An Intent, which can return result data to the caller 1042 * (various data can be attached to Intent "extras"). 1043 */ 1044 public void onActivityResult(int requestCode, int resultCode, Intent data) { 1045 } 1046 1047 /** 1048 * Requests permissions to be granted to this application. These permissions 1049 * must be requested in your manifest, they should not be granted to your app, 1050 * and they should have protection level {@link android.content.pm.PermissionInfo 1051 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by 1052 * the platform or a third-party app. 1053 * <p> 1054 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL} 1055 * are granted at install time if requested in the manifest. Signature permissions 1056 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at 1057 * install time if requested in the manifest and the signature of your app matches 1058 * the signature of the app declaring the permissions. 1059 * </p> 1060 * <p> 1061 * If your app does not have the requested permissions the user will be presented 1062 * with UI for accepting them. After the user has accepted or rejected the 1063 * requested permissions you will receive a callback on {@link 1064 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the 1065 * permissions were granted or not. 1066 * </p> 1067 * <p> 1068 * Note that requesting a permission does not guarantee it will be granted and 1069 * your app should be able to run without having this permission. 1070 * </p> 1071 * <p> 1072 * This method may start an activity allowing the user to choose which permissions 1073 * to grant and which to reject. Hence, you should be prepared that your activity 1074 * may be paused and resumed. Further, granting some permissions may require 1075 * a restart of you application. In such a case, the system will recreate the 1076 * activity stack before delivering the result to {@link 1077 * #onRequestPermissionsResult(int, String[], int[])}. 1078 * </p> 1079 * <p> 1080 * When checking whether you have a permission you should use {@link 1081 * android.content.Context#checkSelfPermission(String)}. 1082 * </p> 1083 * <p> 1084 * Calling this API for permissions already granted to your app would show UI 1085 * to the user to decided whether the app can still hold these permissions. This 1086 * can be useful if the way your app uses the data guarded by the permissions 1087 * changes significantly. 1088 * </p> 1089 * <p> 1090 * A sample permissions request looks like this: 1091 * </p> 1092 * <code><pre><p> 1093 * private void showContacts() { 1094 * if (getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS) 1095 * != PackageManager.PERMISSION_GRANTED) { 1096 * requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 1097 * PERMISSIONS_REQUEST_READ_CONTACTS); 1098 * } else { 1099 * doShowContacts(); 1100 * } 1101 * } 1102 * 1103 * {@literal @}Override 1104 * public void onRequestPermissionsResult(int requestCode, String[] permissions, 1105 * int[] grantResults) { 1106 * if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS 1107 * && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 1108 * doShowContacts(); 1109 * } 1110 * } 1111 * </code></pre></p> 1112 * 1113 * @param permissions The requested permissions. 1114 * @param requestCode Application specific request code to match with a result 1115 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}. 1116 * 1117 * @see #onRequestPermissionsResult(int, String[], int[]) 1118 * @see android.content.Context#checkSelfPermission(String) 1119 */ 1120 public final void requestPermissions(@NonNull String[] permissions, int requestCode) { 1121 if (mHost == null) { 1122 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 1123 } 1124 mHost.onRequestPermissionsFromFragment(this, permissions, requestCode); 1125 } 1126 1127 /** 1128 * Callback for the result from requesting permissions. This method 1129 * is invoked for every call on {@link #requestPermissions(String[], int)}. 1130 * <p> 1131 * <strong>Note:</strong> It is possible that the permissions request interaction 1132 * with the user is interrupted. In this case you will receive empty permissions 1133 * and results arrays which should be treated as a cancellation. 1134 * </p> 1135 * 1136 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}. 1137 * @param permissions The requested permissions. Never null. 1138 * @param grantResults The grant results for the corresponding permissions 1139 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED} 1140 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null. 1141 * 1142 * @see #requestPermissions(String[], int) 1143 */ 1144 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 1145 @NonNull int[] grantResults) { 1146 /* callback - do nothing */ 1147 } 1148 1149 /** 1150 * Gets whether you should show UI with rationale for requesting a permission. 1151 * You should do this only if you do not have the permission and the context in 1152 * which the permission is requested does not clearly communicate to the user 1153 * what would be the benefit from granting this permission. 1154 * <p> 1155 * For example, if you write a camera app, requesting the camera permission 1156 * would be expected by the user and no rationale for why it is requested is 1157 * needed. If however, the app needs location for tagging photos then a non-tech 1158 * savvy user may wonder how location is related to taking photos. In this case 1159 * you may choose to show UI with rationale of requesting this permission. 1160 * </p> 1161 * 1162 * @param permission A permission your app wants to request. 1163 * @return Whether you can show permission rationale UI. 1164 * 1165 * @see Context#checkSelfPermission(String) 1166 * @see #requestPermissions(String[], int) 1167 * @see #onRequestPermissionsResult(int, String[], int[]) 1168 */ 1169 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) { 1170 if (mHost != null) { 1171 return mHost.onShouldShowRequestPermissionRationale(permission); 1172 } 1173 return false; 1174 } 1175 1176 /** 1177 * Returns the LayoutInflater used to inflate Views of this Fragment. The default 1178 * implementation will throw an exception if the Fragment is not attached. 1179 * 1180 * @param savedInstanceState If the fragment is being re-created from 1181 * a previous saved state, this is the state. 1182 * @return The LayoutInflater used to inflate Views of this Fragment. 1183 */ 1184 public LayoutInflater onGetLayoutInflater(Bundle savedInstanceState) { 1185 // TODO: move the implementation in getLayoutInflater to here 1186 return getLayoutInflater(savedInstanceState); 1187 } 1188 1189 /** 1190 * Returns the cached LayoutInflater used to inflate Views of this Fragment. If 1191 * {@link #onGetLayoutInflater(Bundle)} has not been called {@link #onGetLayoutInflater(Bundle)} 1192 * will be called with a {@code null} argument and that value will be cached. 1193 * <p> 1194 * The cached LayoutInflater will be replaced immediately prior to 1195 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} and cleared immediately after 1196 * {@link #onDetach()}. 1197 * 1198 * @return The LayoutInflater used to inflate Views of this Fragment. 1199 */ 1200 public final LayoutInflater getLayoutInflater() { 1201 if (mLayoutInflater == null) { 1202 return performGetLayoutInflater(null); 1203 } 1204 return mLayoutInflater; 1205 } 1206 1207 /** 1208 * Calls {@link #onGetLayoutInflater(Bundle)} and caches the result for use by 1209 * {@link #getLayoutInflater()}. 1210 * 1211 * @param savedInstanceState If the fragment is being re-created from 1212 * a previous saved state, this is the state. 1213 * @return The LayoutInflater used to inflate Views of this Fragment. 1214 */ 1215 LayoutInflater performGetLayoutInflater(Bundle savedInstanceState) { 1216 LayoutInflater layoutInflater = onGetLayoutInflater(savedInstanceState); 1217 mLayoutInflater = layoutInflater; 1218 return mLayoutInflater; 1219 } 1220 1221 /** 1222 * Override {@link #onGetLayoutInflater(Bundle)} when you need to change the 1223 * LayoutInflater or call {@link #getLayoutInflater()} when you want to 1224 * retrieve the current LayoutInflater. 1225 * 1226 * @hide 1227 * @deprecated Override {@link #onGetLayoutInflater(Bundle)} or call 1228 * {@link #getLayoutInflater()} instead of this method. 1229 */ 1230 @Deprecated 1231 @RestrictTo(LIBRARY_GROUP) 1232 public LayoutInflater getLayoutInflater(Bundle savedFragmentState) { 1233 if (mHost == null) { 1234 throw new IllegalStateException("onGetLayoutInflater() cannot be executed until the " 1235 + "Fragment is attached to the FragmentManager."); 1236 } 1237 LayoutInflater result = mHost.onGetLayoutInflater(); 1238 getChildFragmentManager(); // Init if needed; use raw implementation below. 1239 LayoutInflaterCompat.setFactory2(result, mChildFragmentManager.getLayoutInflaterFactory()); 1240 return result; 1241 } 1242 1243 /** 1244 * Called when a fragment is being created as part of a view layout 1245 * inflation, typically from setting the content view of an activity. This 1246 * may be called immediately after the fragment is created from a <fragment> 1247 * tag in a layout file. Note this is <em>before</em> the fragment's 1248 * {@link #onAttach(Activity)} has been called; all you should do here is 1249 * parse the attributes and save them away. 1250 * 1251 * <p>This is called every time the fragment is inflated, even if it is 1252 * being inflated into a new instance with saved state. It typically makes 1253 * sense to re-parse the parameters each time, to allow them to change with 1254 * different configurations.</p> 1255 * 1256 * <p>Here is a typical implementation of a fragment that can take parameters 1257 * both through attributes supplied here as well from {@link #getArguments()}:</p> 1258 * 1259 * {@sample frameworks/support/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentArgumentsSupport.java 1260 * fragment} 1261 * 1262 * <p>Note that parsing the XML attributes uses a "styleable" resource. The 1263 * declaration for the styleable used here is:</p> 1264 * 1265 * {@sample frameworks/support/samples/Support4Demos/res/values/attrs.xml fragment_arguments} 1266 * 1267 * <p>The fragment can then be declared within its activity's content layout 1268 * through a tag like this:</p> 1269 * 1270 * {@sample frameworks/support/samples/Support4Demos/res/layout/fragment_arguments_support.xml from_attributes} 1271 * 1272 * <p>This fragment can also be created dynamically from arguments given 1273 * at runtime in the arguments Bundle; here is an example of doing so at 1274 * creation of the containing activity:</p> 1275 * 1276 * {@sample frameworks/support/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentArgumentsSupport.java 1277 * create} 1278 * 1279 * @param context The Activity that is inflating this fragment. 1280 * @param attrs The attributes at the tag where the fragment is 1281 * being created. 1282 * @param savedInstanceState If the fragment is being re-created from 1283 * a previous saved state, this is the state. 1284 */ 1285 @CallSuper 1286 public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) { 1287 mCalled = true; 1288 final Activity hostActivity = mHost == null ? null : mHost.getActivity(); 1289 if (hostActivity != null) { 1290 mCalled = false; 1291 onInflate(hostActivity, attrs, savedInstanceState); 1292 } 1293 } 1294 1295 /** 1296 * Called when a fragment is being created as part of a view layout 1297 * inflation, typically from setting the content view of an activity. 1298 * 1299 * @deprecated See {@link #onInflate(Context, AttributeSet, Bundle)}. 1300 */ 1301 @Deprecated 1302 @CallSuper 1303 public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) { 1304 mCalled = true; 1305 } 1306 1307 /** 1308 * Called when a fragment is attached as a child of this fragment. 1309 * 1310 * <p>This is called after the attached fragment's <code>onAttach</code> and before 1311 * the attached fragment's <code>onCreate</code> if the fragment has not yet had a previous 1312 * call to <code>onCreate</code>.</p> 1313 * 1314 * @param childFragment child fragment being attached 1315 */ 1316 public void onAttachFragment(Fragment childFragment) { 1317 } 1318 1319 /** 1320 * Called when a fragment is first attached to its context. 1321 * {@link #onCreate(Bundle)} will be called after this. 1322 */ 1323 @CallSuper 1324 public void onAttach(Context context) { 1325 mCalled = true; 1326 final Activity hostActivity = mHost == null ? null : mHost.getActivity(); 1327 if (hostActivity != null) { 1328 mCalled = false; 1329 onAttach(hostActivity); 1330 } 1331 } 1332 1333 /** 1334 * Called when a fragment is first attached to its activity. 1335 * {@link #onCreate(Bundle)} will be called after this. 1336 * 1337 * @deprecated See {@link #onAttach(Context)}. 1338 */ 1339 @Deprecated 1340 @CallSuper 1341 public void onAttach(Activity activity) { 1342 mCalled = true; 1343 } 1344 1345 /** 1346 * Called when a fragment loads an animation. Note that if 1347 * {@link FragmentTransaction#setCustomAnimations(int, int)} was called with 1348 * {@link Animator} resources instead of {@link Animation} resources, {@code nextAnim} 1349 * will be an animator resource. 1350 * 1351 * @param transit The value set in {@link FragmentTransaction#setTransition(int)} or 0 if not 1352 * set. 1353 * @param enter {@code true} when the fragment is added/attached/shown or {@code false} when 1354 * the fragment is removed/detached/hidden. 1355 * @param nextAnim The resource set in 1356 * {@link FragmentTransaction#setCustomAnimations(int, int)}, 1357 * {@link FragmentTransaction#setCustomAnimations(int, int, int, int)}, or 1358 * 0 if neither was called. The value will depend on the current operation. 1359 */ 1360 public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) { 1361 return null; 1362 } 1363 1364 /** 1365 * Called when a fragment loads an animator. This will be called when 1366 * {@link #onCreateAnimation(int, boolean, int)} returns null. Note that if 1367 * {@link FragmentTransaction#setCustomAnimations(int, int)} was called with 1368 * {@link Animation} resources instead of {@link Animator} resources, {@code nextAnim} 1369 * will be an animation resource. 1370 * 1371 * @param transit The value set in {@link FragmentTransaction#setTransition(int)} or 0 if not 1372 * set. 1373 * @param enter {@code true} when the fragment is added/attached/shown or {@code false} when 1374 * the fragment is removed/detached/hidden. 1375 * @param nextAnim The resource set in 1376 * {@link FragmentTransaction#setCustomAnimations(int, int)}, 1377 * {@link FragmentTransaction#setCustomAnimations(int, int, int, int)}, or 1378 * 0 if neither was called. The value will depend on the current operation. 1379 */ 1380 public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) { 1381 return null; 1382 } 1383 1384 /** 1385 * Called to do initial creation of a fragment. This is called after 1386 * {@link #onAttach(Activity)} and before 1387 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}. 1388 * 1389 * <p>Note that this can be called while the fragment's activity is 1390 * still in the process of being created. As such, you can not rely 1391 * on things like the activity's content view hierarchy being initialized 1392 * at this point. If you want to do work once the activity itself is 1393 * created, see {@link #onActivityCreated(Bundle)}. 1394 * 1395 * <p>Any restored child fragments will be created before the base 1396 * <code>Fragment.onCreate</code> method returns.</p> 1397 * 1398 * @param savedInstanceState If the fragment is being re-created from 1399 * a previous saved state, this is the state. 1400 */ 1401 @CallSuper 1402 public void onCreate(@Nullable Bundle savedInstanceState) { 1403 mCalled = true; 1404 restoreChildFragmentState(savedInstanceState); 1405 if (mChildFragmentManager != null 1406 && !mChildFragmentManager.isStateAtLeast(Fragment.CREATED)) { 1407 mChildFragmentManager.dispatchCreate(); 1408 } 1409 } 1410 1411 /** 1412 * Restore the state of the child FragmentManager. Called by either 1413 * {@link #onCreate(Bundle)} for non-retained instance fragments or by 1414 * {@link FragmentManagerImpl#moveToState(Fragment, int, int, int, boolean)} 1415 * for retained instance fragments. 1416 * 1417 * <p><strong>Postcondition:</strong> if there were child fragments to restore, 1418 * the child FragmentManager will be instantiated and brought to the {@link #CREATED} state. 1419 * </p> 1420 * 1421 * @param savedInstanceState the savedInstanceState potentially containing fragment info 1422 */ 1423 void restoreChildFragmentState(@Nullable Bundle savedInstanceState) { 1424 if (savedInstanceState != null) { 1425 Parcelable p = savedInstanceState.getParcelable( 1426 FragmentActivity.FRAGMENTS_TAG); 1427 if (p != null) { 1428 if (mChildFragmentManager == null) { 1429 instantiateChildFragmentManager(); 1430 } 1431 mChildFragmentManager.restoreAllState(p, mChildNonConfig); 1432 mChildNonConfig = null; 1433 mChildFragmentManager.dispatchCreate(); 1434 } 1435 } 1436 } 1437 1438 /** 1439 * Called to have the fragment instantiate its user interface view. 1440 * This is optional, and non-graphical fragments can return null (which 1441 * is the default implementation). This will be called between 1442 * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}. 1443 * 1444 * <p>If you return a View from here, you will later be called in 1445 * {@link #onDestroyView} when the view is being released. 1446 * 1447 * @param inflater The LayoutInflater object that can be used to inflate 1448 * any views in the fragment, 1449 * @param container If non-null, this is the parent view that the fragment's 1450 * UI should be attached to. The fragment should not add the view itself, 1451 * but this can be used to generate the LayoutParams of the view. 1452 * @param savedInstanceState If non-null, this fragment is being re-constructed 1453 * from a previous saved state as given here. 1454 * 1455 * @return Return the View for the fragment's UI, or null. 1456 */ 1457 @Nullable 1458 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, 1459 @Nullable Bundle savedInstanceState) { 1460 return null; 1461 } 1462 1463 /** 1464 * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} 1465 * has returned, but before any saved state has been restored in to the view. 1466 * This gives subclasses a chance to initialize themselves once 1467 * they know their view hierarchy has been completely created. The fragment's 1468 * view hierarchy is not however attached to its parent at this point. 1469 * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}. 1470 * @param savedInstanceState If non-null, this fragment is being re-constructed 1471 * from a previous saved state as given here. 1472 */ 1473 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 1474 } 1475 1476 /** 1477 * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}), 1478 * if provided. 1479 * 1480 * @return The fragment's root view, or null if it has no layout. 1481 */ 1482 @Nullable 1483 public View getView() { 1484 return mView; 1485 } 1486 1487 /** 1488 * Called when the fragment's activity has been created and this 1489 * fragment's view hierarchy instantiated. It can be used to do final 1490 * initialization once these pieces are in place, such as retrieving 1491 * views or restoring state. It is also useful for fragments that use 1492 * {@link #setRetainInstance(boolean)} to retain their instance, 1493 * as this callback tells the fragment when it is fully associated with 1494 * the new activity instance. This is called after {@link #onCreateView} 1495 * and before {@link #onViewStateRestored(Bundle)}. 1496 * 1497 * @param savedInstanceState If the fragment is being re-created from 1498 * a previous saved state, this is the state. 1499 */ 1500 @CallSuper 1501 public void onActivityCreated(@Nullable Bundle savedInstanceState) { 1502 mCalled = true; 1503 } 1504 1505 /** 1506 * Called when all saved state has been restored into the view hierarchy 1507 * of the fragment. This can be used to do initialization based on saved 1508 * state that you are letting the view hierarchy track itself, such as 1509 * whether check box widgets are currently checked. This is called 1510 * after {@link #onActivityCreated(Bundle)} and before 1511 * {@link #onStart()}. 1512 * 1513 * @param savedInstanceState If the fragment is being re-created from 1514 * a previous saved state, this is the state. 1515 */ 1516 @CallSuper 1517 public void onViewStateRestored(@Nullable Bundle savedInstanceState) { 1518 mCalled = true; 1519 } 1520 1521 /** 1522 * Called when the Fragment is visible to the user. This is generally 1523 * tied to {@link Activity#onStart() Activity.onStart} of the containing 1524 * Activity's lifecycle. 1525 */ 1526 @CallSuper 1527 public void onStart() { 1528 mCalled = true; 1529 1530 if (!mLoadersStarted) { 1531 mLoadersStarted = true; 1532 if (!mCheckedForLoaderManager) { 1533 mCheckedForLoaderManager = true; 1534 mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false); 1535 } else if (mLoaderManager != null) { 1536 mLoaderManager.doStart(); 1537 } 1538 } 1539 } 1540 1541 /** 1542 * Called when the fragment is visible to the user and actively running. 1543 * This is generally 1544 * tied to {@link Activity#onResume() Activity.onResume} of the containing 1545 * Activity's lifecycle. 1546 */ 1547 @CallSuper 1548 public void onResume() { 1549 mCalled = true; 1550 } 1551 1552 /** 1553 * Called to ask the fragment to save its current dynamic state, so it 1554 * can later be reconstructed in a new instance of its process is 1555 * restarted. If a new instance of the fragment later needs to be 1556 * created, the data you place in the Bundle here will be available 1557 * in the Bundle given to {@link #onCreate(Bundle)}, 1558 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and 1559 * {@link #onActivityCreated(Bundle)}. 1560 * 1561 * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle) 1562 * Activity.onSaveInstanceState(Bundle)} and most of the discussion there 1563 * applies here as well. Note however: <em>this method may be called 1564 * at any time before {@link #onDestroy()}</em>. There are many situations 1565 * where a fragment may be mostly torn down (such as when placed on the 1566 * back stack with no UI showing), but its state will not be saved until 1567 * its owning activity actually needs to save its state. 1568 * 1569 * @param outState Bundle in which to place your saved state. 1570 */ 1571 public void onSaveInstanceState(Bundle outState) { 1572 } 1573 1574 /** 1575 * Called when the Fragment's activity changes from fullscreen mode to multi-window mode and 1576 * visa-versa. This is generally tied to {@link Activity#onMultiWindowModeChanged} of the 1577 * containing Activity. 1578 * 1579 * @param isInMultiWindowMode True if the activity is in multi-window mode. 1580 */ 1581 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) { 1582 } 1583 1584 /** 1585 * Called by the system when the activity changes to and from picture-in-picture mode. This is 1586 * generally tied to {@link Activity#onPictureInPictureModeChanged} of the containing Activity. 1587 * 1588 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode. 1589 */ 1590 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) { 1591 } 1592 1593 @Override 1594 @CallSuper 1595 public void onConfigurationChanged(Configuration newConfig) { 1596 mCalled = true; 1597 } 1598 1599 /** 1600 * Called when the Fragment is no longer resumed. This is generally 1601 * tied to {@link Activity#onPause() Activity.onPause} of the containing 1602 * Activity's lifecycle. 1603 */ 1604 @CallSuper 1605 public void onPause() { 1606 mCalled = true; 1607 } 1608 1609 /** 1610 * Called when the Fragment is no longer started. This is generally 1611 * tied to {@link Activity#onStop() Activity.onStop} of the containing 1612 * Activity's lifecycle. 1613 */ 1614 @CallSuper 1615 public void onStop() { 1616 mCalled = true; 1617 } 1618 1619 @Override 1620 @CallSuper 1621 public void onLowMemory() { 1622 mCalled = true; 1623 } 1624 1625 /** 1626 * Called when the view previously created by {@link #onCreateView} has 1627 * been detached from the fragment. The next time the fragment needs 1628 * to be displayed, a new view will be created. This is called 1629 * after {@link #onStop()} and before {@link #onDestroy()}. It is called 1630 * <em>regardless</em> of whether {@link #onCreateView} returned a 1631 * non-null view. Internally it is called after the view's state has 1632 * been saved but before it has been removed from its parent. 1633 */ 1634 @CallSuper 1635 public void onDestroyView() { 1636 mCalled = true; 1637 } 1638 1639 /** 1640 * Called when the fragment is no longer in use. This is called 1641 * after {@link #onStop()} and before {@link #onDetach()}. 1642 */ 1643 @CallSuper 1644 public void onDestroy() { 1645 mCalled = true; 1646 //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager 1647 // + " mLoaderManager=" + mLoaderManager); 1648 if (!mCheckedForLoaderManager) { 1649 mCheckedForLoaderManager = true; 1650 mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false); 1651 } 1652 if (mLoaderManager != null) { 1653 mLoaderManager.doDestroy(); 1654 } 1655 } 1656 1657 /** 1658 * Called by the fragment manager once this fragment has been removed, 1659 * so that we don't have any left-over state if the application decides 1660 * to re-use the instance. This only clears state that the framework 1661 * internally manages, not things the application sets. 1662 */ 1663 void initState() { 1664 mIndex = -1; 1665 mWho = null; 1666 mAdded = false; 1667 mRemoving = false; 1668 mFromLayout = false; 1669 mInLayout = false; 1670 mRestored = false; 1671 mBackStackNesting = 0; 1672 mFragmentManager = null; 1673 mChildFragmentManager = null; 1674 mHost = null; 1675 mFragmentId = 0; 1676 mContainerId = 0; 1677 mTag = null; 1678 mHidden = false; 1679 mDetached = false; 1680 mRetaining = false; 1681 mLoaderManager = null; 1682 mLoadersStarted = false; 1683 mCheckedForLoaderManager = false; 1684 } 1685 1686 /** 1687 * Called when the fragment is no longer attached to its activity. This 1688 * is called after {@link #onDestroy()}. 1689 */ 1690 @CallSuper 1691 public void onDetach() { 1692 mCalled = true; 1693 } 1694 1695 /** 1696 * Initialize the contents of the Fragment host's standard options menu. You 1697 * should place your menu items in to <var>menu</var>. For this method 1698 * to be called, you must have first called {@link #setHasOptionsMenu}. See 1699 * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu} 1700 * for more information. 1701 * 1702 * @param menu The options menu in which you place your items. 1703 * 1704 * @see #setHasOptionsMenu 1705 * @see #onPrepareOptionsMenu 1706 * @see #onOptionsItemSelected 1707 */ 1708 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 1709 } 1710 1711 /** 1712 * Prepare the Fragment host's standard options menu to be displayed. This is 1713 * called right before the menu is shown, every time it is shown. You can 1714 * use this method to efficiently enable/disable items or otherwise 1715 * dynamically modify the contents. See 1716 * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu} 1717 * for more information. 1718 * 1719 * @param menu The options menu as last shown or first initialized by 1720 * onCreateOptionsMenu(). 1721 * 1722 * @see #setHasOptionsMenu 1723 * @see #onCreateOptionsMenu 1724 */ 1725 public void onPrepareOptionsMenu(Menu menu) { 1726 } 1727 1728 /** 1729 * Called when this fragment's option menu items are no longer being 1730 * included in the overall options menu. Receiving this call means that 1731 * the menu needed to be rebuilt, but this fragment's items were not 1732 * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)} 1733 * was not called). 1734 */ 1735 public void onDestroyOptionsMenu() { 1736 } 1737 1738 /** 1739 * This hook is called whenever an item in your options menu is selected. 1740 * The default implementation simply returns false to have the normal 1741 * processing happen (calling the item's Runnable or sending a message to 1742 * its Handler as appropriate). You can use this method for any items 1743 * for which you would like to do processing without those other 1744 * facilities. 1745 * 1746 * <p>Derived classes should call through to the base class for it to 1747 * perform the default menu handling. 1748 * 1749 * @param item The menu item that was selected. 1750 * 1751 * @return boolean Return false to allow normal menu processing to 1752 * proceed, true to consume it here. 1753 * 1754 * @see #onCreateOptionsMenu 1755 */ 1756 public boolean onOptionsItemSelected(MenuItem item) { 1757 return false; 1758 } 1759 1760 /** 1761 * This hook is called whenever the options menu is being closed (either by the user canceling 1762 * the menu with the back/menu button, or when an item is selected). 1763 * 1764 * @param menu The options menu as last shown or first initialized by 1765 * onCreateOptionsMenu(). 1766 */ 1767 public void onOptionsMenuClosed(Menu menu) { 1768 } 1769 1770 /** 1771 * Called when a context menu for the {@code view} is about to be shown. 1772 * Unlike {@link #onCreateOptionsMenu}, this will be called every 1773 * time the context menu is about to be shown and should be populated for 1774 * the view (or item inside the view for {@link AdapterView} subclasses, 1775 * this can be found in the {@code menuInfo})). 1776 * <p> 1777 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an 1778 * item has been selected. 1779 * <p> 1780 * The default implementation calls up to 1781 * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though 1782 * you can not call this implementation if you don't want that behavior. 1783 * <p> 1784 * It is not safe to hold onto the context menu after this method returns. 1785 * {@inheritDoc} 1786 */ 1787 @Override 1788 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 1789 getActivity().onCreateContextMenu(menu, v, menuInfo); 1790 } 1791 1792 /** 1793 * Registers a context menu to be shown for the given view (multiple views 1794 * can show the context menu). This method will set the 1795 * {@link OnCreateContextMenuListener} on the view to this fragment, so 1796 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be 1797 * called when it is time to show the context menu. 1798 * 1799 * @see #unregisterForContextMenu(View) 1800 * @param view The view that should show a context menu. 1801 */ 1802 public void registerForContextMenu(View view) { 1803 view.setOnCreateContextMenuListener(this); 1804 } 1805 1806 /** 1807 * Prevents a context menu to be shown for the given view. This method will 1808 * remove the {@link OnCreateContextMenuListener} on the view. 1809 * 1810 * @see #registerForContextMenu(View) 1811 * @param view The view that should stop showing a context menu. 1812 */ 1813 public void unregisterForContextMenu(View view) { 1814 view.setOnCreateContextMenuListener(null); 1815 } 1816 1817 /** 1818 * This hook is called whenever an item in a context menu is selected. The 1819 * default implementation simply returns false to have the normal processing 1820 * happen (calling the item's Runnable or sending a message to its Handler 1821 * as appropriate). You can use this method for any items for which you 1822 * would like to do processing without those other facilities. 1823 * <p> 1824 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the 1825 * View that added this menu item. 1826 * <p> 1827 * Derived classes should call through to the base class for it to perform 1828 * the default menu handling. 1829 * 1830 * @param item The context menu item that was selected. 1831 * @return boolean Return false to allow normal context menu processing to 1832 * proceed, true to consume it here. 1833 */ 1834 public boolean onContextItemSelected(MenuItem item) { 1835 return false; 1836 } 1837 1838 /** 1839 * When custom transitions are used with Fragments, the enter transition callback 1840 * is called when this Fragment is attached or detached when not popping the back stack. 1841 * 1842 * @param callback Used to manipulate the shared element transitions on this Fragment 1843 * when added not as a pop from the back stack. 1844 */ 1845 public void setEnterSharedElementCallback(SharedElementCallback callback) { 1846 ensureAnimationInfo().mEnterTransitionCallback = callback; 1847 } 1848 1849 /** 1850 * When custom transitions are used with Fragments, the exit transition callback 1851 * is called when this Fragment is attached or detached when popping the back stack. 1852 * 1853 * @param callback Used to manipulate the shared element transitions on this Fragment 1854 * when added as a pop from the back stack. 1855 */ 1856 public void setExitSharedElementCallback(SharedElementCallback callback) { 1857 ensureAnimationInfo().mExitTransitionCallback = callback; 1858 } 1859 1860 /** 1861 * Sets the Transition that will be used to move Views into the initial scene. The entering 1862 * Views will be those that are regular Views or ViewGroups that have 1863 * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 1864 * {@link android.transition.Visibility} as entering is governed by changing visibility from 1865 * {@link View#INVISIBLE} to {@link View#VISIBLE}. If <code>transition</code> is null, 1866 * entering Views will remain unaffected. 1867 * 1868 * @param transition The Transition to use to move Views into the initial Scene. 1869 */ 1870 public void setEnterTransition(Object transition) { 1871 ensureAnimationInfo().mEnterTransition = transition; 1872 } 1873 1874 /** 1875 * Returns the Transition that will be used to move Views into the initial scene. The entering 1876 * Views will be those that are regular Views or ViewGroups that have 1877 * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 1878 * {@link android.transition.Visibility} as entering is governed by changing visibility from 1879 * {@link View#INVISIBLE} to {@link View#VISIBLE}. 1880 * 1881 * @return the Transition to use to move Views into the initial Scene. 1882 */ 1883 public Object getEnterTransition() { 1884 if (mAnimationInfo == null) { 1885 return null; 1886 } 1887 return mAnimationInfo.mEnterTransition; 1888 } 1889 1890 /** 1891 * Sets the Transition that will be used to move Views out of the scene when the Fragment is 1892 * preparing to be removed, hidden, or detached because of popping the back stack. The exiting 1893 * Views will be those that are regular Views or ViewGroups that have 1894 * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 1895 * {@link android.transition.Visibility} as entering is governed by changing visibility from 1896 * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null, 1897 * entering Views will remain unaffected. If nothing is set, the default will be to 1898 * use the same value as set in {@link #setEnterTransition(Object)}. 1899 * 1900 * @param transition The Transition to use to move Views out of the Scene when the Fragment 1901 * is preparing to close. <code>transition</code> must be an 1902 * android.transition.Transition. 1903 */ 1904 public void setReturnTransition(Object transition) { 1905 ensureAnimationInfo().mReturnTransition = transition; 1906 } 1907 1908 /** 1909 * Returns the Transition that will be used to move Views out of the scene when the Fragment is 1910 * preparing to be removed, hidden, or detached because of popping the back stack. The exiting 1911 * Views will be those that are regular Views or ViewGroups that have 1912 * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 1913 * {@link android.transition.Visibility} as entering is governed by changing visibility from 1914 * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null, 1915 * entering Views will remain unaffected. 1916 * 1917 * @return the Transition to use to move Views out of the Scene when the Fragment 1918 * is preparing to close. 1919 */ 1920 public Object getReturnTransition() { 1921 if (mAnimationInfo == null) { 1922 return null; 1923 } 1924 return mAnimationInfo.mReturnTransition == USE_DEFAULT_TRANSITION ? getEnterTransition() 1925 : mAnimationInfo.mReturnTransition; 1926 } 1927 1928 /** 1929 * Sets the Transition that will be used to move Views out of the scene when the 1930 * fragment is removed, hidden, or detached when not popping the back stack. 1931 * The exiting Views will be those that are regular Views or ViewGroups that 1932 * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 1933 * {@link android.transition.Visibility} as exiting is governed by changing visibility 1934 * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will 1935 * remain unaffected. 1936 * 1937 * @param transition The Transition to use to move Views out of the Scene when the Fragment 1938 * is being closed not due to popping the back stack. <code>transition</code> 1939 * must be an android.transition.Transition. 1940 */ 1941 public void setExitTransition(Object transition) { 1942 ensureAnimationInfo().mExitTransition = transition; 1943 } 1944 1945 /** 1946 * Returns the Transition that will be used to move Views out of the scene when the 1947 * fragment is removed, hidden, or detached when not popping the back stack. 1948 * The exiting Views will be those that are regular Views or ViewGroups that 1949 * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 1950 * {@link android.transition.Visibility} as exiting is governed by changing visibility 1951 * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will 1952 * remain unaffected. 1953 * 1954 * @return the Transition to use to move Views out of the Scene when the Fragment 1955 * is being closed not due to popping the back stack. 1956 */ 1957 public Object getExitTransition() { 1958 if (mAnimationInfo == null) { 1959 return null; 1960 } 1961 return mAnimationInfo.mExitTransition; 1962 } 1963 1964 /** 1965 * Sets the Transition that will be used to move Views in to the scene when returning due 1966 * to popping a back stack. The entering Views will be those that are regular Views 1967 * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions 1968 * will extend {@link android.transition.Visibility} as exiting is governed by changing 1969 * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, 1970 * the views will remain unaffected. If nothing is set, the default will be to use the same 1971 * transition as {@link #setExitTransition(Object)}. 1972 * 1973 * @param transition The Transition to use to move Views into the scene when reentering from a 1974 * previously-started Activity. <code>transition</code> 1975 * must be an android.transition.Transition. 1976 */ 1977 public void setReenterTransition(Object transition) { 1978 ensureAnimationInfo().mReenterTransition = transition; 1979 } 1980 1981 /** 1982 * Returns the Transition that will be used to move Views in to the scene when returning due 1983 * to popping a back stack. The entering Views will be those that are regular Views 1984 * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions 1985 * will extend {@link android.transition.Visibility} as exiting is governed by changing 1986 * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, 1987 * the views will remain unaffected. If nothing is set, the default will be to use the same 1988 * transition as {@link #setExitTransition(Object)}. 1989 * 1990 * @return the Transition to use to move Views into the scene when reentering from a 1991 * previously-started Activity. 1992 */ 1993 public Object getReenterTransition() { 1994 if (mAnimationInfo == null) { 1995 return null; 1996 } 1997 return mAnimationInfo.mReenterTransition == USE_DEFAULT_TRANSITION ? getExitTransition() 1998 : mAnimationInfo.mReenterTransition; 1999 } 2000 2001 /** 2002 * Sets the Transition that will be used for shared elements transferred into the content 2003 * Scene. Typical Transitions will affect size and location, such as 2004 * {@link android.transition.ChangeBounds}. A null 2005 * value will cause transferred shared elements to blink to the final position. 2006 * 2007 * @param transition The Transition to use for shared elements transferred into the content 2008 * Scene. <code>transition</code> must be an android.transition.Transition. 2009 */ 2010 public void setSharedElementEnterTransition(Object transition) { 2011 ensureAnimationInfo().mSharedElementEnterTransition = transition; 2012 } 2013 2014 /** 2015 * Returns the Transition that will be used for shared elements transferred into the content 2016 * Scene. Typical Transitions will affect size and location, such as 2017 * {@link android.transition.ChangeBounds}. A null 2018 * value will cause transferred shared elements to blink to the final position. 2019 * 2020 * @return The Transition to use for shared elements transferred into the content 2021 * Scene. 2022 */ 2023 public Object getSharedElementEnterTransition() { 2024 if (mAnimationInfo == null) { 2025 return null; 2026 } 2027 return mAnimationInfo.mSharedElementEnterTransition; 2028 } 2029 2030 /** 2031 * Sets the Transition that will be used for shared elements transferred back during a 2032 * pop of the back stack. This Transition acts in the leaving Fragment. 2033 * Typical Transitions will affect size and location, such as 2034 * {@link android.transition.ChangeBounds}. A null 2035 * value will cause transferred shared elements to blink to the final position. 2036 * If no value is set, the default will be to use the same value as 2037 * {@link #setSharedElementEnterTransition(Object)}. 2038 * 2039 * @param transition The Transition to use for shared elements transferred out of the content 2040 * Scene. <code>transition</code> must be an android.transition.Transition. 2041 */ 2042 public void setSharedElementReturnTransition(Object transition) { 2043 ensureAnimationInfo().mSharedElementReturnTransition = transition; 2044 } 2045 2046 /** 2047 * Return the Transition that will be used for shared elements transferred back during a 2048 * pop of the back stack. This Transition acts in the leaving Fragment. 2049 * Typical Transitions will affect size and location, such as 2050 * {@link android.transition.ChangeBounds}. A null 2051 * value will cause transferred shared elements to blink to the final position. 2052 * If no value is set, the default will be to use the same value as 2053 * {@link #setSharedElementEnterTransition(Object)}. 2054 * 2055 * @return The Transition to use for shared elements transferred out of the content 2056 * Scene. 2057 */ 2058 public Object getSharedElementReturnTransition() { 2059 if (mAnimationInfo == null) { 2060 return null; 2061 } 2062 return mAnimationInfo.mSharedElementReturnTransition == USE_DEFAULT_TRANSITION 2063 ? getSharedElementEnterTransition() 2064 : mAnimationInfo.mSharedElementReturnTransition; 2065 } 2066 2067 /** 2068 * Sets whether the the exit transition and enter transition overlap or not. 2069 * When true, the enter transition will start as soon as possible. When false, the 2070 * enter transition will wait until the exit transition completes before starting. 2071 * 2072 * @param allow true to start the enter transition when possible or false to 2073 * wait until the exiting transition completes. 2074 */ 2075 public void setAllowEnterTransitionOverlap(boolean allow) { 2076 ensureAnimationInfo().mAllowEnterTransitionOverlap = allow; 2077 } 2078 2079 /** 2080 * Returns whether the the exit transition and enter transition overlap or not. 2081 * When true, the enter transition will start as soon as possible. When false, the 2082 * enter transition will wait until the exit transition completes before starting. 2083 * 2084 * @return true when the enter transition should start as soon as possible or false to 2085 * when it should wait until the exiting transition completes. 2086 */ 2087 public boolean getAllowEnterTransitionOverlap() { 2088 return (mAnimationInfo == null || mAnimationInfo.mAllowEnterTransitionOverlap == null) 2089 ? true : mAnimationInfo.mAllowEnterTransitionOverlap; 2090 } 2091 2092 /** 2093 * Sets whether the the return transition and reenter transition overlap or not. 2094 * When true, the reenter transition will start as soon as possible. When false, the 2095 * reenter transition will wait until the return transition completes before starting. 2096 * 2097 * @param allow true to start the reenter transition when possible or false to wait until the 2098 * return transition completes. 2099 */ 2100 public void setAllowReturnTransitionOverlap(boolean allow) { 2101 ensureAnimationInfo().mAllowReturnTransitionOverlap = allow; 2102 } 2103 2104 /** 2105 * Returns whether the the return transition and reenter transition overlap or not. 2106 * When true, the reenter transition will start as soon as possible. When false, the 2107 * reenter transition will wait until the return transition completes before starting. 2108 * 2109 * @return true to start the reenter transition when possible or false to wait until the 2110 * return transition completes. 2111 */ 2112 public boolean getAllowReturnTransitionOverlap() { 2113 return (mAnimationInfo == null || mAnimationInfo.mAllowReturnTransitionOverlap == null) 2114 ? true : mAnimationInfo.mAllowReturnTransitionOverlap; 2115 } 2116 2117 /** 2118 * Postpone the entering Fragment transition until {@link #startPostponedEnterTransition()} 2119 * or {@link FragmentManager#executePendingTransactions()} has been called. 2120 * <p> 2121 * This method gives the Fragment the ability to delay Fragment animations 2122 * until all data is loaded. Until then, the added, shown, and 2123 * attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't 2124 * be have their Views removed. The transaction runs when all postponed added Fragments in the 2125 * transaction have called {@link #startPostponedEnterTransition()}. 2126 * <p> 2127 * This method should be called before being added to the FragmentTransaction or 2128 * in {@link #onCreate(Bundle), {@link #onAttach(Context)}, or 2129 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}}. 2130 * {@link #startPostponedEnterTransition()} must be called to allow the Fragment to 2131 * start the transitions. 2132 * <p> 2133 * When a FragmentTransaction is started that may affect a postponed FragmentTransaction, 2134 * based on which containers are in their operations, the postponed FragmentTransaction 2135 * will have its start triggered. The early triggering may result in faulty or nonexistent 2136 * animations in the postponed transaction. FragmentTransactions that operate only on 2137 * independent containers will not interfere with each other's postponement. 2138 * <p> 2139 * Calling postponeEnterTransition on Fragments with a null View will not postpone the 2140 * transition. Likewise, postponement only works if 2141 * {@link FragmentTransaction#setReorderingAllowed(boolean) FragmentTransaction reordering} is 2142 * enabled. 2143 * 2144 * @see Activity#postponeEnterTransition() 2145 * @see FragmentTransaction#setReorderingAllowed(boolean) 2146 */ 2147 public void postponeEnterTransition() { 2148 ensureAnimationInfo().mEnterTransitionPostponed = true; 2149 } 2150 2151 /** 2152 * Begin postponed transitions after {@link #postponeEnterTransition()} was called. 2153 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition() 2154 * or {@link FragmentManager#executePendingTransactions()} to complete the FragmentTransaction. 2155 * If postponement was interrupted with {@link FragmentManager#executePendingTransactions()}, 2156 * before {@code startPostponedEnterTransition()}, animations may not run or may execute 2157 * improperly. 2158 * 2159 * @see Activity#startPostponedEnterTransition() 2160 */ 2161 public void startPostponedEnterTransition() { 2162 if (mFragmentManager == null || mFragmentManager.mHost == null) { 2163 ensureAnimationInfo().mEnterTransitionPostponed = false; 2164 } else if (Looper.myLooper() != mFragmentManager.mHost.getHandler().getLooper()) { 2165 mFragmentManager.mHost.getHandler().postAtFrontOfQueue(new Runnable() { 2166 @Override 2167 public void run() { 2168 callStartTransitionListener(); 2169 } 2170 }); 2171 } else { 2172 callStartTransitionListener(); 2173 } 2174 } 2175 2176 /** 2177 * Calls the start transition listener. This must be called on the UI thread. 2178 */ 2179 private void callStartTransitionListener() { 2180 final OnStartEnterTransitionListener listener; 2181 if (mAnimationInfo == null) { 2182 listener = null; 2183 } else { 2184 mAnimationInfo.mEnterTransitionPostponed = false; 2185 listener = mAnimationInfo.mStartEnterTransitionListener; 2186 mAnimationInfo.mStartEnterTransitionListener = null; 2187 } 2188 if (listener != null) { 2189 listener.onStartEnterTransition(); 2190 } 2191 } 2192 2193 /** 2194 * Print the Fragments's state into the given stream. 2195 * 2196 * @param prefix Text to print at the front of each line. 2197 * @param fd The raw file descriptor that the dump is being sent to. 2198 * @param writer The PrintWriter to which you should dump your state. This will be 2199 * closed for you after you return. 2200 * @param args additional arguments to the dump request. 2201 */ 2202 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 2203 writer.print(prefix); writer.print("mFragmentId=#"); 2204 writer.print(Integer.toHexString(mFragmentId)); 2205 writer.print(" mContainerId=#"); 2206 writer.print(Integer.toHexString(mContainerId)); 2207 writer.print(" mTag="); writer.println(mTag); 2208 writer.print(prefix); writer.print("mState="); writer.print(mState); 2209 writer.print(" mIndex="); writer.print(mIndex); 2210 writer.print(" mWho="); writer.print(mWho); 2211 writer.print(" mBackStackNesting="); writer.println(mBackStackNesting); 2212 writer.print(prefix); writer.print("mAdded="); writer.print(mAdded); 2213 writer.print(" mRemoving="); writer.print(mRemoving); 2214 writer.print(" mFromLayout="); writer.print(mFromLayout); 2215 writer.print(" mInLayout="); writer.println(mInLayout); 2216 writer.print(prefix); writer.print("mHidden="); writer.print(mHidden); 2217 writer.print(" mDetached="); writer.print(mDetached); 2218 writer.print(" mMenuVisible="); writer.print(mMenuVisible); 2219 writer.print(" mHasMenu="); writer.println(mHasMenu); 2220 writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance); 2221 writer.print(" mRetaining="); writer.print(mRetaining); 2222 writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint); 2223 if (mFragmentManager != null) { 2224 writer.print(prefix); writer.print("mFragmentManager="); 2225 writer.println(mFragmentManager); 2226 } 2227 if (mHost != null) { 2228 writer.print(prefix); writer.print("mHost="); 2229 writer.println(mHost); 2230 } 2231 if (mParentFragment != null) { 2232 writer.print(prefix); writer.print("mParentFragment="); 2233 writer.println(mParentFragment); 2234 } 2235 if (mArguments != null) { 2236 writer.print(prefix); writer.print("mArguments="); writer.println(mArguments); 2237 } 2238 if (mSavedFragmentState != null) { 2239 writer.print(prefix); writer.print("mSavedFragmentState="); 2240 writer.println(mSavedFragmentState); 2241 } 2242 if (mSavedViewState != null) { 2243 writer.print(prefix); writer.print("mSavedViewState="); 2244 writer.println(mSavedViewState); 2245 } 2246 if (mTarget != null) { 2247 writer.print(prefix); writer.print("mTarget="); writer.print(mTarget); 2248 writer.print(" mTargetRequestCode="); 2249 writer.println(mTargetRequestCode); 2250 } 2251 if (getNextAnim() != 0) { 2252 writer.print(prefix); writer.print("mNextAnim="); writer.println(getNextAnim()); 2253 } 2254 if (mContainer != null) { 2255 writer.print(prefix); writer.print("mContainer="); writer.println(mContainer); 2256 } 2257 if (mView != null) { 2258 writer.print(prefix); writer.print("mView="); writer.println(mView); 2259 } 2260 if (mInnerView != null) { 2261 writer.print(prefix); writer.print("mInnerView="); writer.println(mView); 2262 } 2263 if (getAnimatingAway() != null) { 2264 writer.print(prefix); 2265 writer.print("mAnimatingAway="); 2266 writer.println(getAnimatingAway()); 2267 writer.print(prefix); 2268 writer.print("mStateAfterAnimating="); 2269 writer.println(getStateAfterAnimating()); 2270 } 2271 if (mLoaderManager != null) { 2272 writer.print(prefix); writer.println("Loader Manager:"); 2273 mLoaderManager.dump(prefix + " ", fd, writer, args); 2274 } 2275 if (mChildFragmentManager != null) { 2276 writer.print(prefix); writer.println("Child " + mChildFragmentManager + ":"); 2277 mChildFragmentManager.dump(prefix + " ", fd, writer, args); 2278 } 2279 } 2280 2281 Fragment findFragmentByWho(String who) { 2282 if (who.equals(mWho)) { 2283 return this; 2284 } 2285 if (mChildFragmentManager != null) { 2286 return mChildFragmentManager.findFragmentByWho(who); 2287 } 2288 return null; 2289 } 2290 2291 void instantiateChildFragmentManager() { 2292 if (mHost == null) { 2293 throw new IllegalStateException("Fragment has not been attached yet."); 2294 } 2295 mChildFragmentManager = new FragmentManagerImpl(); 2296 mChildFragmentManager.attachController(mHost, new FragmentContainer() { 2297 @Override 2298 @Nullable 2299 public View onFindViewById(int id) { 2300 if (mView == null) { 2301 throw new IllegalStateException("Fragment does not have a view"); 2302 } 2303 return mView.findViewById(id); 2304 } 2305 2306 @Override 2307 public boolean onHasView() { 2308 return (mView != null); 2309 } 2310 2311 @Override 2312 public Fragment instantiate(Context context, String className, Bundle arguments) { 2313 return mHost.instantiate(context, className, arguments); 2314 } 2315 }, this); 2316 } 2317 2318 void performCreate(Bundle savedInstanceState) { 2319 if (mChildFragmentManager != null) { 2320 mChildFragmentManager.noteStateNotSaved(); 2321 } 2322 mState = CREATED; 2323 mCalled = false; 2324 onCreate(savedInstanceState); 2325 if (!mCalled) { 2326 throw new SuperNotCalledException("Fragment " + this 2327 + " did not call through to super.onCreate()"); 2328 } 2329 } 2330 2331 View performCreateView(LayoutInflater inflater, ViewGroup container, 2332 Bundle savedInstanceState) { 2333 if (mChildFragmentManager != null) { 2334 mChildFragmentManager.noteStateNotSaved(); 2335 } 2336 mPerformedCreateView = true; 2337 return onCreateView(inflater, container, savedInstanceState); 2338 } 2339 2340 void performActivityCreated(Bundle savedInstanceState) { 2341 if (mChildFragmentManager != null) { 2342 mChildFragmentManager.noteStateNotSaved(); 2343 } 2344 mState = ACTIVITY_CREATED; 2345 mCalled = false; 2346 onActivityCreated(savedInstanceState); 2347 if (!mCalled) { 2348 throw new SuperNotCalledException("Fragment " + this 2349 + " did not call through to super.onActivityCreated()"); 2350 } 2351 if (mChildFragmentManager != null) { 2352 mChildFragmentManager.dispatchActivityCreated(); 2353 } 2354 } 2355 2356 void performStart() { 2357 if (mChildFragmentManager != null) { 2358 mChildFragmentManager.noteStateNotSaved(); 2359 mChildFragmentManager.execPendingActions(); 2360 } 2361 mState = STARTED; 2362 mCalled = false; 2363 onStart(); 2364 if (!mCalled) { 2365 throw new SuperNotCalledException("Fragment " + this 2366 + " did not call through to super.onStart()"); 2367 } 2368 if (mChildFragmentManager != null) { 2369 mChildFragmentManager.dispatchStart(); 2370 } 2371 if (mLoaderManager != null) { 2372 mLoaderManager.doReportStart(); 2373 } 2374 } 2375 2376 void performResume() { 2377 if (mChildFragmentManager != null) { 2378 mChildFragmentManager.noteStateNotSaved(); 2379 mChildFragmentManager.execPendingActions(); 2380 } 2381 mState = RESUMED; 2382 mCalled = false; 2383 onResume(); 2384 if (!mCalled) { 2385 throw new SuperNotCalledException("Fragment " + this 2386 + " did not call through to super.onResume()"); 2387 } 2388 if (mChildFragmentManager != null) { 2389 mChildFragmentManager.dispatchResume(); 2390 mChildFragmentManager.execPendingActions(); 2391 } 2392 } 2393 2394 void noteStateNotSaved() { 2395 if (mChildFragmentManager != null) { 2396 mChildFragmentManager.noteStateNotSaved(); 2397 } 2398 } 2399 2400 void performMultiWindowModeChanged(boolean isInMultiWindowMode) { 2401 onMultiWindowModeChanged(isInMultiWindowMode); 2402 if (mChildFragmentManager != null) { 2403 mChildFragmentManager.dispatchMultiWindowModeChanged(isInMultiWindowMode); 2404 } 2405 } 2406 2407 void performPictureInPictureModeChanged(boolean isInPictureInPictureMode) { 2408 onPictureInPictureModeChanged(isInPictureInPictureMode); 2409 if (mChildFragmentManager != null) { 2410 mChildFragmentManager.dispatchPictureInPictureModeChanged(isInPictureInPictureMode); 2411 } 2412 } 2413 2414 void performConfigurationChanged(Configuration newConfig) { 2415 onConfigurationChanged(newConfig); 2416 if (mChildFragmentManager != null) { 2417 mChildFragmentManager.dispatchConfigurationChanged(newConfig); 2418 } 2419 } 2420 2421 void performLowMemory() { 2422 onLowMemory(); 2423 if (mChildFragmentManager != null) { 2424 mChildFragmentManager.dispatchLowMemory(); 2425 } 2426 } 2427 2428 /* 2429 void performTrimMemory(int level) { 2430 onTrimMemory(level); 2431 if (mChildFragmentManager != null) { 2432 mChildFragmentManager.dispatchTrimMemory(level); 2433 } 2434 } 2435 */ 2436 2437 boolean performCreateOptionsMenu(Menu menu, MenuInflater inflater) { 2438 boolean show = false; 2439 if (!mHidden) { 2440 if (mHasMenu && mMenuVisible) { 2441 show = true; 2442 onCreateOptionsMenu(menu, inflater); 2443 } 2444 if (mChildFragmentManager != null) { 2445 show |= mChildFragmentManager.dispatchCreateOptionsMenu(menu, inflater); 2446 } 2447 } 2448 return show; 2449 } 2450 2451 boolean performPrepareOptionsMenu(Menu menu) { 2452 boolean show = false; 2453 if (!mHidden) { 2454 if (mHasMenu && mMenuVisible) { 2455 show = true; 2456 onPrepareOptionsMenu(menu); 2457 } 2458 if (mChildFragmentManager != null) { 2459 show |= mChildFragmentManager.dispatchPrepareOptionsMenu(menu); 2460 } 2461 } 2462 return show; 2463 } 2464 2465 boolean performOptionsItemSelected(MenuItem item) { 2466 if (!mHidden) { 2467 if (mHasMenu && mMenuVisible) { 2468 if (onOptionsItemSelected(item)) { 2469 return true; 2470 } 2471 } 2472 if (mChildFragmentManager != null) { 2473 if (mChildFragmentManager.dispatchOptionsItemSelected(item)) { 2474 return true; 2475 } 2476 } 2477 } 2478 return false; 2479 } 2480 2481 boolean performContextItemSelected(MenuItem item) { 2482 if (!mHidden) { 2483 if (onContextItemSelected(item)) { 2484 return true; 2485 } 2486 if (mChildFragmentManager != null) { 2487 if (mChildFragmentManager.dispatchContextItemSelected(item)) { 2488 return true; 2489 } 2490 } 2491 } 2492 return false; 2493 } 2494 2495 void performOptionsMenuClosed(Menu menu) { 2496 if (!mHidden) { 2497 if (mHasMenu && mMenuVisible) { 2498 onOptionsMenuClosed(menu); 2499 } 2500 if (mChildFragmentManager != null) { 2501 mChildFragmentManager.dispatchOptionsMenuClosed(menu); 2502 } 2503 } 2504 } 2505 2506 void performSaveInstanceState(Bundle outState) { 2507 onSaveInstanceState(outState); 2508 if (mChildFragmentManager != null) { 2509 Parcelable p = mChildFragmentManager.saveAllState(); 2510 if (p != null) { 2511 outState.putParcelable(FragmentActivity.FRAGMENTS_TAG, p); 2512 } 2513 } 2514 } 2515 2516 void performPause() { 2517 if (mChildFragmentManager != null) { 2518 mChildFragmentManager.dispatchPause(); 2519 } 2520 mState = STARTED; 2521 mCalled = false; 2522 onPause(); 2523 if (!mCalled) { 2524 throw new SuperNotCalledException("Fragment " + this 2525 + " did not call through to super.onPause()"); 2526 } 2527 } 2528 2529 void performStop() { 2530 if (mChildFragmentManager != null) { 2531 mChildFragmentManager.dispatchStop(); 2532 } 2533 mState = STOPPED; 2534 mCalled = false; 2535 onStop(); 2536 if (!mCalled) { 2537 throw new SuperNotCalledException("Fragment " + this 2538 + " did not call through to super.onStop()"); 2539 } 2540 } 2541 2542 void performReallyStop() { 2543 if (mChildFragmentManager != null) { 2544 mChildFragmentManager.dispatchReallyStop(); 2545 } 2546 mState = ACTIVITY_CREATED; 2547 if (mLoadersStarted) { 2548 mLoadersStarted = false; 2549 if (!mCheckedForLoaderManager) { 2550 mCheckedForLoaderManager = true; 2551 mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false); 2552 } 2553 if (mLoaderManager != null) { 2554 if (mHost.getRetainLoaders()) { 2555 mLoaderManager.doRetain(); 2556 } else { 2557 mLoaderManager.doStop(); 2558 } 2559 } 2560 } 2561 } 2562 2563 void performDestroyView() { 2564 if (mChildFragmentManager != null) { 2565 mChildFragmentManager.dispatchDestroyView(); 2566 } 2567 mState = CREATED; 2568 mCalled = false; 2569 onDestroyView(); 2570 if (!mCalled) { 2571 throw new SuperNotCalledException("Fragment " + this 2572 + " did not call through to super.onDestroyView()"); 2573 } 2574 if (mLoaderManager != null) { 2575 mLoaderManager.doReportNextStart(); 2576 } 2577 mPerformedCreateView = false; 2578 } 2579 2580 void performDestroy() { 2581 if (mChildFragmentManager != null) { 2582 mChildFragmentManager.dispatchDestroy(); 2583 } 2584 mState = INITIALIZING; 2585 mCalled = false; 2586 onDestroy(); 2587 if (!mCalled) { 2588 throw new SuperNotCalledException("Fragment " + this 2589 + " did not call through to super.onDestroy()"); 2590 } 2591 mChildFragmentManager = null; 2592 } 2593 2594 void performDetach() { 2595 mCalled = false; 2596 onDetach(); 2597 mLayoutInflater = null; 2598 if (!mCalled) { 2599 throw new SuperNotCalledException("Fragment " + this 2600 + " did not call through to super.onDetach()"); 2601 } 2602 2603 // Destroy the child FragmentManager if we still have it here. 2604 // We won't unless we're retaining our instance and if we do, 2605 // our child FragmentManager instance state will have already been saved. 2606 if (mChildFragmentManager != null) { 2607 if (!mRetaining) { 2608 throw new IllegalStateException("Child FragmentManager of " + this + " was not " 2609 + " destroyed and this fragment is not retaining instance"); 2610 } 2611 mChildFragmentManager.dispatchDestroy(); 2612 mChildFragmentManager = null; 2613 } 2614 } 2615 2616 void setOnStartEnterTransitionListener(OnStartEnterTransitionListener listener) { 2617 ensureAnimationInfo(); 2618 if (listener == mAnimationInfo.mStartEnterTransitionListener) { 2619 return; 2620 } 2621 if (listener != null && mAnimationInfo.mStartEnterTransitionListener != null) { 2622 throw new IllegalStateException("Trying to set a replacement " 2623 + "startPostponedEnterTransition on " + this); 2624 } 2625 if (mAnimationInfo.mEnterTransitionPostponed) { 2626 mAnimationInfo.mStartEnterTransitionListener = listener; 2627 } 2628 if (listener != null) { 2629 listener.startListening(); 2630 } 2631 } 2632 2633 private AnimationInfo ensureAnimationInfo() { 2634 if (mAnimationInfo == null) { 2635 mAnimationInfo = new AnimationInfo(); 2636 } 2637 return mAnimationInfo; 2638 } 2639 2640 int getNextAnim() { 2641 if (mAnimationInfo == null) { 2642 return 0; 2643 } 2644 return mAnimationInfo.mNextAnim; 2645 } 2646 2647 void setNextAnim(int animResourceId) { 2648 if (mAnimationInfo == null && animResourceId == 0) { 2649 return; // no change! 2650 } 2651 ensureAnimationInfo().mNextAnim = animResourceId; 2652 } 2653 2654 int getNextTransition() { 2655 if (mAnimationInfo == null) { 2656 return 0; 2657 } 2658 return mAnimationInfo.mNextTransition; 2659 } 2660 2661 void setNextTransition(int nextTransition, int nextTransitionStyle) { 2662 if (mAnimationInfo == null && nextTransition == 0 && nextTransitionStyle == 0) { 2663 return; // no change! 2664 } 2665 ensureAnimationInfo(); 2666 mAnimationInfo.mNextTransition = nextTransition; 2667 mAnimationInfo.mNextTransitionStyle = nextTransitionStyle; 2668 } 2669 2670 int getNextTransitionStyle() { 2671 if (mAnimationInfo == null) { 2672 return 0; 2673 } 2674 return mAnimationInfo.mNextTransitionStyle; 2675 } 2676 2677 SharedElementCallback getEnterTransitionCallback() { 2678 if (mAnimationInfo == null) { 2679 return null; 2680 } 2681 return mAnimationInfo.mEnterTransitionCallback; 2682 } 2683 2684 SharedElementCallback getExitTransitionCallback() { 2685 if (mAnimationInfo == null) { 2686 return null; 2687 } 2688 return mAnimationInfo.mExitTransitionCallback; 2689 } 2690 2691 View getAnimatingAway() { 2692 if (mAnimationInfo == null) { 2693 return null; 2694 } 2695 return mAnimationInfo.mAnimatingAway; 2696 } 2697 2698 void setAnimatingAway(View view) { 2699 ensureAnimationInfo().mAnimatingAway = view; 2700 } 2701 2702 void setAnimator(Animator animator) { 2703 ensureAnimationInfo().mAnimator = animator; 2704 } 2705 2706 Animator getAnimator() { 2707 if (mAnimationInfo == null) { 2708 return null; 2709 } 2710 return mAnimationInfo.mAnimator; 2711 } 2712 2713 int getStateAfterAnimating() { 2714 if (mAnimationInfo == null) { 2715 return 0; 2716 } 2717 return mAnimationInfo.mStateAfterAnimating; 2718 } 2719 2720 void setStateAfterAnimating(int state) { 2721 ensureAnimationInfo().mStateAfterAnimating = state; 2722 } 2723 2724 boolean isPostponed() { 2725 if (mAnimationInfo == null) { 2726 return false; 2727 } 2728 return mAnimationInfo.mEnterTransitionPostponed; 2729 } 2730 2731 boolean isHideReplaced() { 2732 if (mAnimationInfo == null) { 2733 return false; 2734 } 2735 return mAnimationInfo.mIsHideReplaced; 2736 } 2737 2738 void setHideReplaced(boolean replaced) { 2739 ensureAnimationInfo().mIsHideReplaced = replaced; 2740 } 2741 2742 /** 2743 * Used internally to be notified when {@link #startPostponedEnterTransition()} has 2744 * been called. This listener will only be called once and then be removed from the 2745 * listeners. 2746 */ 2747 interface OnStartEnterTransitionListener { 2748 void onStartEnterTransition(); 2749 void startListening(); 2750 } 2751 2752 /** 2753 * Contains all the animation and transition information for a fragment. This will only 2754 * be instantiated for Fragments that have Views. 2755 */ 2756 static class AnimationInfo { 2757 // Non-null if the fragment's view hierarchy is currently animating away, 2758 // meaning we need to wait a bit on completely destroying it. This is the 2759 // view that is animating. 2760 View mAnimatingAway; 2761 2762 // Non-null if the fragment's view hierarchy is currently animating away with an 2763 // animator instead of an animation. 2764 Animator mAnimator; 2765 2766 // If mAnimatingAway != null, this is the state we should move to once the 2767 // animation is done. 2768 int mStateAfterAnimating; 2769 2770 // If app has requested a specific animation, this is the one to use. 2771 int mNextAnim; 2772 2773 // If app has requested a specific transition, this is the one to use. 2774 int mNextTransition; 2775 2776 // If app has requested a specific transition style, this is the one to use. 2777 int mNextTransitionStyle; 2778 2779 private Object mEnterTransition = null; 2780 private Object mReturnTransition = USE_DEFAULT_TRANSITION; 2781 private Object mExitTransition = null; 2782 private Object mReenterTransition = USE_DEFAULT_TRANSITION; 2783 private Object mSharedElementEnterTransition = null; 2784 private Object mSharedElementReturnTransition = USE_DEFAULT_TRANSITION; 2785 private Boolean mAllowReturnTransitionOverlap; 2786 private Boolean mAllowEnterTransitionOverlap; 2787 2788 SharedElementCallback mEnterTransitionCallback = null; 2789 SharedElementCallback mExitTransitionCallback = null; 2790 2791 // True when postponeEnterTransition has been called and startPostponeEnterTransition 2792 // hasn't been called yet. 2793 boolean mEnterTransitionPostponed; 2794 2795 // Listener to wait for startPostponeEnterTransition. After being called, it will 2796 // be set to null 2797 OnStartEnterTransitionListener mStartEnterTransitionListener; 2798 2799 // True if the View was hidden, but the transition is handling the hide 2800 boolean mIsHideReplaced; 2801 } 2802} 2803