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