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