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