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