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