Fragment.java revision 5af42fc3052ecaf35c937278a986143a65f6ce5f
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. This method provides the same configuration that will be sent in the 1720 * following {@link #onConfigurationChanged(Configuration)} call after the activity enters this 1721 * mode. 1722 * 1723 * @param isInMultiWindowMode True if the activity is in multi-window mode. 1724 * @param newConfig The new configuration of the activity with the state 1725 * {@param isInMultiWindowMode}. 1726 */ 1727 public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) { 1728 onMultiWindowModeChanged(isInMultiWindowMode); 1729 } 1730 1731 /** 1732 * Called when the Fragment's activity changes from fullscreen mode to multi-window mode and 1733 * visa-versa. This is generally tied to {@link Activity#onMultiWindowModeChanged} of the 1734 * containing Activity. 1735 * 1736 * @param isInMultiWindowMode True if the activity is in multi-window mode. 1737 * 1738 * @deprecated Use {@link #onMultiWindowModeChanged(boolean, Configuration)} instead. 1739 */ 1740 @Deprecated 1741 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) { 1742 } 1743 1744 /** 1745 * Called by the system when the activity changes to and from picture-in-picture mode. This is 1746 * generally tied to {@link Activity#onPictureInPictureModeChanged} of the containing Activity. 1747 * This method provides the same configuration that will be sent in the following 1748 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode. 1749 * 1750 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode. 1751 * @param newConfig The new configuration of the activity with the state 1752 * {@param isInPictureInPictureMode}. 1753 */ 1754 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, 1755 Configuration newConfig) { 1756 onPictureInPictureModeChanged(isInPictureInPictureMode); 1757 } 1758 1759 /** 1760 * Called by the system when the activity changes to and from picture-in-picture mode. This is 1761 * generally tied to {@link Activity#onPictureInPictureModeChanged} of the containing Activity. 1762 * 1763 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode. 1764 * 1765 * @deprecated Use {@link #onPictureInPictureModeChanged(boolean, Configuration)} instead. 1766 */ 1767 @Deprecated 1768 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) { 1769 } 1770 1771 @CallSuper 1772 public void onConfigurationChanged(Configuration newConfig) { 1773 mCalled = true; 1774 } 1775 1776 /** 1777 * Called when the Fragment is no longer resumed. This is generally 1778 * tied to {@link Activity#onPause() Activity.onPause} of the containing 1779 * Activity's lifecycle. 1780 */ 1781 @CallSuper 1782 public void onPause() { 1783 mCalled = true; 1784 } 1785 1786 /** 1787 * Called when the Fragment is no longer started. This is generally 1788 * tied to {@link Activity#onStop() Activity.onStop} of the containing 1789 * Activity's lifecycle. 1790 */ 1791 @CallSuper 1792 public void onStop() { 1793 mCalled = true; 1794 } 1795 1796 @CallSuper 1797 public void onLowMemory() { 1798 mCalled = true; 1799 } 1800 1801 @CallSuper 1802 public void onTrimMemory(int level) { 1803 mCalled = true; 1804 } 1805 1806 /** 1807 * Called when the view previously created by {@link #onCreateView} has 1808 * been detached from the fragment. The next time the fragment needs 1809 * to be displayed, a new view will be created. This is called 1810 * after {@link #onStop()} and before {@link #onDestroy()}. It is called 1811 * <em>regardless</em> of whether {@link #onCreateView} returned a 1812 * non-null view. Internally it is called after the view's state has 1813 * been saved but before it has been removed from its parent. 1814 */ 1815 @CallSuper 1816 public void onDestroyView() { 1817 mCalled = true; 1818 } 1819 1820 /** 1821 * Called when the fragment is no longer in use. This is called 1822 * after {@link #onStop()} and before {@link #onDetach()}. 1823 */ 1824 @CallSuper 1825 public void onDestroy() { 1826 mCalled = true; 1827 //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager 1828 // + " mLoaderManager=" + mLoaderManager); 1829 if (!mCheckedForLoaderManager) { 1830 mCheckedForLoaderManager = true; 1831 mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false); 1832 } 1833 if (mLoaderManager != null) { 1834 mLoaderManager.doDestroy(); 1835 } 1836 } 1837 1838 /** 1839 * Called by the fragment manager once this fragment has been removed, 1840 * so that we don't have any left-over state if the application decides 1841 * to re-use the instance. This only clears state that the framework 1842 * internally manages, not things the application sets. 1843 */ 1844 void initState() { 1845 mIndex = -1; 1846 mWho = null; 1847 mAdded = false; 1848 mRemoving = false; 1849 mFromLayout = false; 1850 mInLayout = false; 1851 mRestored = false; 1852 mBackStackNesting = 0; 1853 mFragmentManager = null; 1854 mChildFragmentManager = null; 1855 mHost = null; 1856 mFragmentId = 0; 1857 mContainerId = 0; 1858 mTag = null; 1859 mHidden = false; 1860 mDetached = false; 1861 mRetaining = false; 1862 mLoaderManager = null; 1863 mLoadersStarted = false; 1864 mCheckedForLoaderManager = false; 1865 } 1866 1867 /** 1868 * Called when the fragment is no longer attached to its activity. This is called after 1869 * {@link #onDestroy()}, except in the cases where the fragment instance is retained across 1870 * Activity re-creation (see {@link #setRetainInstance(boolean)}), in which case it is called 1871 * after {@link #onStop()}. 1872 */ 1873 @CallSuper 1874 public void onDetach() { 1875 mCalled = true; 1876 } 1877 1878 /** 1879 * Initialize the contents of the Activity's standard options menu. You 1880 * should place your menu items in to <var>menu</var>. For this method 1881 * to be called, you must have first called {@link #setHasOptionsMenu}. See 1882 * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu} 1883 * for more information. 1884 * 1885 * @param menu The options menu in which you place your items. 1886 * 1887 * @see #setHasOptionsMenu 1888 * @see #onPrepareOptionsMenu 1889 * @see #onOptionsItemSelected 1890 */ 1891 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 1892 } 1893 1894 /** 1895 * Prepare the Screen's standard options menu to be displayed. This is 1896 * called right before the menu is shown, every time it is shown. You can 1897 * use this method to efficiently enable/disable items or otherwise 1898 * dynamically modify the contents. See 1899 * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu} 1900 * for more information. 1901 * 1902 * @param menu The options menu as last shown or first initialized by 1903 * onCreateOptionsMenu(). 1904 * 1905 * @see #setHasOptionsMenu 1906 * @see #onCreateOptionsMenu 1907 */ 1908 public void onPrepareOptionsMenu(Menu menu) { 1909 } 1910 1911 /** 1912 * Called when this fragment's option menu items are no longer being 1913 * included in the overall options menu. Receiving this call means that 1914 * the menu needed to be rebuilt, but this fragment's items were not 1915 * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)} 1916 * was not called). 1917 */ 1918 public void onDestroyOptionsMenu() { 1919 } 1920 1921 /** 1922 * This hook is called whenever an item in your options menu is selected. 1923 * The default implementation simply returns false to have the normal 1924 * processing happen (calling the item's Runnable or sending a message to 1925 * its Handler as appropriate). You can use this method for any items 1926 * for which you would like to do processing without those other 1927 * facilities. 1928 * 1929 * <p>Derived classes should call through to the base class for it to 1930 * perform the default menu handling. 1931 * 1932 * @param item The menu item that was selected. 1933 * 1934 * @return boolean Return false to allow normal menu processing to 1935 * proceed, true to consume it here. 1936 * 1937 * @see #onCreateOptionsMenu 1938 */ 1939 public boolean onOptionsItemSelected(MenuItem item) { 1940 return false; 1941 } 1942 1943 /** 1944 * This hook is called whenever the options menu is being closed (either by the user canceling 1945 * the menu with the back/menu button, or when an item is selected). 1946 * 1947 * @param menu The options menu as last shown or first initialized by 1948 * onCreateOptionsMenu(). 1949 */ 1950 public void onOptionsMenuClosed(Menu menu) { 1951 } 1952 1953 /** 1954 * Called when a context menu for the {@code view} is about to be shown. 1955 * Unlike {@link #onCreateOptionsMenu}, this will be called every 1956 * time the context menu is about to be shown and should be populated for 1957 * the view (or item inside the view for {@link AdapterView} subclasses, 1958 * this can be found in the {@code menuInfo})). 1959 * <p> 1960 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an 1961 * item has been selected. 1962 * <p> 1963 * The default implementation calls up to 1964 * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though 1965 * you can not call this implementation if you don't want that behavior. 1966 * <p> 1967 * It is not safe to hold onto the context menu after this method returns. 1968 * {@inheritDoc} 1969 */ 1970 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 1971 getActivity().onCreateContextMenu(menu, v, menuInfo); 1972 } 1973 1974 /** 1975 * Registers a context menu to be shown for the given view (multiple views 1976 * can show the context menu). This method will set the 1977 * {@link OnCreateContextMenuListener} on the view to this fragment, so 1978 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be 1979 * called when it is time to show the context menu. 1980 * 1981 * @see #unregisterForContextMenu(View) 1982 * @param view The view that should show a context menu. 1983 */ 1984 public void registerForContextMenu(View view) { 1985 view.setOnCreateContextMenuListener(this); 1986 } 1987 1988 /** 1989 * Prevents a context menu to be shown for the given view. This method will 1990 * remove the {@link OnCreateContextMenuListener} on the view. 1991 * 1992 * @see #registerForContextMenu(View) 1993 * @param view The view that should stop showing a context menu. 1994 */ 1995 public void unregisterForContextMenu(View view) { 1996 view.setOnCreateContextMenuListener(null); 1997 } 1998 1999 /** 2000 * This hook is called whenever an item in a context menu is selected. The 2001 * default implementation simply returns false to have the normal processing 2002 * happen (calling the item's Runnable or sending a message to its Handler 2003 * as appropriate). You can use this method for any items for which you 2004 * would like to do processing without those other facilities. 2005 * <p> 2006 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the 2007 * View that added this menu item. 2008 * <p> 2009 * Derived classes should call through to the base class for it to perform 2010 * the default menu handling. 2011 * 2012 * @param item The context menu item that was selected. 2013 * @return boolean Return false to allow normal context menu processing to 2014 * proceed, true to consume it here. 2015 */ 2016 public boolean onContextItemSelected(MenuItem item) { 2017 return false; 2018 } 2019 2020 /** 2021 * When custom transitions are used with Fragments, the enter transition callback 2022 * is called when this Fragment is attached or detached when not popping the back stack. 2023 * 2024 * @param callback Used to manipulate the shared element transitions on this Fragment 2025 * when added not as a pop from the back stack. 2026 */ 2027 public void setEnterSharedElementCallback(SharedElementCallback callback) { 2028 if (callback == null) { 2029 if (mAnimationInfo == null) { 2030 return; // already a null callback 2031 } 2032 callback = SharedElementCallback.NULL_CALLBACK; 2033 } 2034 ensureAnimationInfo().mEnterTransitionCallback = callback; 2035 } 2036 2037 /** 2038 * When custom transitions are used with Fragments, the exit transition callback 2039 * is called when this Fragment is attached or detached when popping the back stack. 2040 * 2041 * @param callback Used to manipulate the shared element transitions on this Fragment 2042 * when added as a pop from the back stack. 2043 */ 2044 public void setExitSharedElementCallback(SharedElementCallback callback) { 2045 if (callback == null) { 2046 if (mAnimationInfo == null) { 2047 return; // already a null callback 2048 } 2049 callback = SharedElementCallback.NULL_CALLBACK; 2050 } 2051 ensureAnimationInfo().mExitTransitionCallback = callback; 2052 } 2053 2054 /** 2055 * Sets the Transition that will be used to move Views into the initial scene. The entering 2056 * Views will be those that are regular Views or ViewGroups that have 2057 * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 2058 * {@link android.transition.Visibility} as entering is governed by changing visibility from 2059 * {@link View#INVISIBLE} to {@link View#VISIBLE}. If <code>transition</code> is null, 2060 * entering Views will remain unaffected. 2061 * 2062 * @param transition The Transition to use to move Views into the initial Scene. 2063 * @attr ref android.R.styleable#Fragment_fragmentEnterTransition 2064 */ 2065 public void setEnterTransition(Transition transition) { 2066 if (shouldChangeTransition(transition, null)) { 2067 ensureAnimationInfo().mEnterTransition = transition; 2068 } 2069 } 2070 2071 /** 2072 * Returns the Transition that will be used to move Views into the initial scene. The entering 2073 * Views will be those that are regular Views or ViewGroups that have 2074 * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 2075 * {@link android.transition.Visibility} as entering is governed by changing visibility from 2076 * {@link View#INVISIBLE} to {@link View#VISIBLE}. 2077 * 2078 * @return the Transition to use to move Views into the initial Scene. 2079 * @attr ref android.R.styleable#Fragment_fragmentEnterTransition 2080 */ 2081 public Transition getEnterTransition() { 2082 if (mAnimationInfo == null) { 2083 return null; 2084 } 2085 return mAnimationInfo.mEnterTransition; 2086 } 2087 2088 /** 2089 * Sets the Transition that will be used to move Views out of the scene when the Fragment is 2090 * preparing to be removed, hidden, or detached because of popping the back stack. The exiting 2091 * Views will be those that are regular Views or ViewGroups that have 2092 * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 2093 * {@link android.transition.Visibility} as entering is governed by changing visibility from 2094 * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null, 2095 * entering Views will remain unaffected. If nothing is set, the default will be to 2096 * use the same value as set in {@link #setEnterTransition(android.transition.Transition)}. 2097 * 2098 * @param transition The Transition to use to move Views out of the Scene when the Fragment 2099 * is preparing to close. 2100 * @attr ref android.R.styleable#Fragment_fragmentExitTransition 2101 */ 2102 public void setReturnTransition(Transition transition) { 2103 if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) { 2104 ensureAnimationInfo().mReturnTransition = transition; 2105 } 2106 } 2107 2108 /** 2109 * Returns the Transition that will be used to move Views out of the scene when the Fragment is 2110 * preparing to be removed, hidden, or detached because of popping the back stack. The exiting 2111 * Views will be those that are regular Views or ViewGroups that have 2112 * {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 2113 * {@link android.transition.Visibility} as entering is governed by changing visibility from 2114 * {@link View#VISIBLE} to {@link View#INVISIBLE}. If <code>transition</code> is null, 2115 * entering Views will remain unaffected. 2116 * 2117 * @return the Transition to use to move Views out of the Scene when the Fragment 2118 * is preparing to close. 2119 * @attr ref android.R.styleable#Fragment_fragmentExitTransition 2120 */ 2121 public Transition getReturnTransition() { 2122 if (mAnimationInfo == null) { 2123 return null; 2124 } 2125 return mAnimationInfo.mReturnTransition == USE_DEFAULT_TRANSITION ? getEnterTransition() 2126 : mAnimationInfo.mReturnTransition; 2127 } 2128 2129 /** 2130 * Sets the Transition that will be used to move Views out of the scene when the 2131 * fragment is removed, hidden, or detached when not popping the back stack. 2132 * The exiting Views will be those that are regular Views or ViewGroups that 2133 * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 2134 * {@link android.transition.Visibility} as exiting is governed by changing visibility 2135 * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will 2136 * remain unaffected. 2137 * 2138 * @param transition The Transition to use to move Views out of the Scene when the Fragment 2139 * is being closed not due to popping the back stack. 2140 * @attr ref android.R.styleable#Fragment_fragmentExitTransition 2141 */ 2142 public void setExitTransition(Transition transition) { 2143 if (shouldChangeTransition(transition, null)) { 2144 ensureAnimationInfo().mExitTransition = transition; 2145 } 2146 } 2147 2148 /** 2149 * Returns the Transition that will be used to move Views out of the scene when the 2150 * fragment is removed, hidden, or detached when not popping the back stack. 2151 * The exiting Views will be those that are regular Views or ViewGroups that 2152 * have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions will extend 2153 * {@link android.transition.Visibility} as exiting is governed by changing visibility 2154 * from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, the views will 2155 * remain unaffected. 2156 * 2157 * @return the Transition to use to move Views out of the Scene when the Fragment 2158 * is being closed not due to popping the back stack. 2159 * @attr ref android.R.styleable#Fragment_fragmentExitTransition 2160 */ 2161 public Transition getExitTransition() { 2162 if (mAnimationInfo == null) { 2163 return null; 2164 } 2165 return mAnimationInfo.mExitTransition; 2166 } 2167 2168 /** 2169 * Sets the Transition that will be used to move Views in to the scene when returning due 2170 * to popping a back stack. The entering Views will be those that are regular Views 2171 * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions 2172 * will extend {@link android.transition.Visibility} as exiting is governed by changing 2173 * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, 2174 * the views will remain unaffected. If nothing is set, the default will be to use the same 2175 * transition as {@link #setExitTransition(android.transition.Transition)}. 2176 * 2177 * @param transition The Transition to use to move Views into the scene when reentering from a 2178 * previously-started Activity. 2179 * @attr ref android.R.styleable#Fragment_fragmentReenterTransition 2180 */ 2181 public void setReenterTransition(Transition transition) { 2182 if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) { 2183 ensureAnimationInfo().mReenterTransition = transition; 2184 } 2185 } 2186 2187 /** 2188 * Returns the Transition that will be used to move Views in to the scene when returning due 2189 * to popping a back stack. The entering Views will be those that are regular Views 2190 * or ViewGroups that have {@link ViewGroup#isTransitionGroup} return true. Typical Transitions 2191 * will extend {@link android.transition.Visibility} as exiting is governed by changing 2192 * visibility from {@link View#VISIBLE} to {@link View#INVISIBLE}. If transition is null, 2193 * the views will remain unaffected. If nothing is set, the default will be to use the same 2194 * transition as {@link #setExitTransition(android.transition.Transition)}. 2195 * 2196 * @return the Transition to use to move Views into the scene when reentering from a 2197 * previously-started Activity. 2198 * @attr ref android.R.styleable#Fragment_fragmentReenterTransition 2199 */ 2200 public Transition getReenterTransition() { 2201 if (mAnimationInfo == null) { 2202 return null; 2203 } 2204 return mAnimationInfo.mReenterTransition == USE_DEFAULT_TRANSITION ? getExitTransition() 2205 : mAnimationInfo.mReenterTransition; 2206 } 2207 2208 /** 2209 * Sets the Transition that will be used for shared elements transferred into the content 2210 * Scene. Typical Transitions will affect size and location, such as 2211 * {@link android.transition.ChangeBounds}. A null 2212 * value will cause transferred shared elements to blink to the final position. 2213 * 2214 * @param transition The Transition to use for shared elements transferred into the content 2215 * Scene. 2216 * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition 2217 */ 2218 public void setSharedElementEnterTransition(Transition transition) { 2219 if (shouldChangeTransition(transition, null)) { 2220 ensureAnimationInfo().mSharedElementEnterTransition = transition; 2221 } 2222 } 2223 2224 /** 2225 * Returns the Transition that will be used for shared elements transferred into the content 2226 * Scene. Typical Transitions will affect size and location, such as 2227 * {@link android.transition.ChangeBounds}. A null 2228 * value will cause transferred shared elements to blink to the final position. 2229 * 2230 * @return The Transition to use for shared elements transferred into the content 2231 * Scene. 2232 * @attr ref android.R.styleable#Fragment_fragmentSharedElementEnterTransition 2233 */ 2234 public Transition getSharedElementEnterTransition() { 2235 if (mAnimationInfo == null) { 2236 return null; 2237 } 2238 return mAnimationInfo.mSharedElementEnterTransition; 2239 } 2240 2241 /** 2242 * Sets the Transition that will be used for shared elements transferred back during a 2243 * pop of the back stack. This Transition acts in the leaving Fragment. 2244 * Typical Transitions will affect size and location, such as 2245 * {@link android.transition.ChangeBounds}. A null 2246 * value will cause transferred shared elements to blink to the final position. 2247 * If no value is set, the default will be to use the same value as 2248 * {@link #setSharedElementEnterTransition(android.transition.Transition)}. 2249 * 2250 * @param transition The Transition to use for shared elements transferred out of the content 2251 * Scene. 2252 * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition 2253 */ 2254 public void setSharedElementReturnTransition(Transition transition) { 2255 if (shouldChangeTransition(transition, USE_DEFAULT_TRANSITION)) { 2256 ensureAnimationInfo().mSharedElementReturnTransition = transition; 2257 } 2258 } 2259 2260 /** 2261 * Return the Transition that will be used for shared elements transferred back during a 2262 * pop of the back stack. This Transition acts in the leaving Fragment. 2263 * Typical Transitions will affect size and location, such as 2264 * {@link android.transition.ChangeBounds}. A null 2265 * value will cause transferred shared elements to blink to the final position. 2266 * If no value is set, the default will be to use the same value as 2267 * {@link #setSharedElementEnterTransition(android.transition.Transition)}. 2268 * 2269 * @return The Transition to use for shared elements transferred out of the content 2270 * Scene. 2271 * @attr ref android.R.styleable#Fragment_fragmentSharedElementReturnTransition 2272 */ 2273 public Transition getSharedElementReturnTransition() { 2274 if (mAnimationInfo == null) { 2275 return null; 2276 } 2277 return mAnimationInfo.mSharedElementReturnTransition == USE_DEFAULT_TRANSITION 2278 ? getSharedElementEnterTransition() 2279 : mAnimationInfo.mSharedElementReturnTransition; 2280 } 2281 2282 /** 2283 * Sets whether the the exit transition and enter transition overlap or not. 2284 * When true, the enter transition will start as soon as possible. When false, the 2285 * enter transition will wait until the exit transition completes before starting. 2286 * 2287 * @param allow true to start the enter transition when possible or false to 2288 * wait until the exiting transition completes. 2289 * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap 2290 */ 2291 public void setAllowEnterTransitionOverlap(boolean allow) { 2292 ensureAnimationInfo().mAllowEnterTransitionOverlap = allow; 2293 } 2294 2295 /** 2296 * Returns whether the the exit transition and enter transition overlap or not. 2297 * When true, the enter transition will start as soon as possible. When false, the 2298 * enter transition will wait until the exit transition completes before starting. 2299 * 2300 * @return true when the enter transition should start as soon as possible or false to 2301 * when it should wait until the exiting transition completes. 2302 * @attr ref android.R.styleable#Fragment_fragmentAllowEnterTransitionOverlap 2303 */ 2304 public boolean getAllowEnterTransitionOverlap() { 2305 return (mAnimationInfo == null || mAnimationInfo.mAllowEnterTransitionOverlap == null) 2306 ? true : mAnimationInfo.mAllowEnterTransitionOverlap; 2307 } 2308 2309 /** 2310 * Sets whether the the return transition and reenter transition overlap or not. 2311 * When true, the reenter transition will start as soon as possible. When false, the 2312 * reenter transition will wait until the return transition completes before starting. 2313 * 2314 * @param allow true to start the reenter transition when possible or false to wait until the 2315 * return transition completes. 2316 * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap 2317 */ 2318 public void setAllowReturnTransitionOverlap(boolean allow) { 2319 ensureAnimationInfo().mAllowReturnTransitionOverlap = allow; 2320 } 2321 2322 /** 2323 * Returns whether the the return transition and reenter transition overlap or not. 2324 * When true, the reenter transition will start as soon as possible. When false, the 2325 * reenter transition will wait until the return transition completes before starting. 2326 * 2327 * @return true to start the reenter transition when possible or false to wait until the 2328 * return transition completes. 2329 * @attr ref android.R.styleable#Fragment_fragmentAllowReturnTransitionOverlap 2330 */ 2331 public boolean getAllowReturnTransitionOverlap() { 2332 return (mAnimationInfo == null || mAnimationInfo.mAllowReturnTransitionOverlap == null) 2333 ? true : mAnimationInfo.mAllowReturnTransitionOverlap; 2334 } 2335 2336 /** 2337 * Postpone the entering Fragment transition until {@link #startPostponedEnterTransition()} 2338 * or {@link FragmentManager#executePendingTransactions()} has been called. 2339 * <p> 2340 * This method gives the Fragment the ability to delay Fragment animations 2341 * until all data is loaded. Until then, the added, shown, and 2342 * attached Fragments will be INVISIBLE and removed, hidden, and detached Fragments won't 2343 * be have their Views removed. The transaction runs when all postponed added Fragments in the 2344 * transaction have called {@link #startPostponedEnterTransition()}. 2345 * <p> 2346 * This method should be called before being added to the FragmentTransaction or 2347 * in {@link #onCreate(Bundle), {@link #onAttach(Context)}, or 2348 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}}. 2349 * {@link #startPostponedEnterTransition()} must be called to allow the Fragment to 2350 * start the transitions. 2351 * <p> 2352 * When a FragmentTransaction is started that may affect a postponed FragmentTransaction, 2353 * based on which containers are in their operations, the postponed FragmentTransaction 2354 * will have its start triggered. The early triggering may result in faulty or nonexistent 2355 * animations in the postponed transaction. FragmentTransactions that operate only on 2356 * independent containers will not interfere with each other's postponement. 2357 * <p> 2358 * Calling postponeEnterTransition on Fragments with a null View will not postpone the 2359 * transition. Likewise, postponement only works if FragmentTransaction optimizations are 2360 * enabled. 2361 * 2362 * @see Activity#postponeEnterTransition() 2363 * @see FragmentTransaction#setAllowOptimization(boolean) 2364 */ 2365 public void postponeEnterTransition() { 2366 ensureAnimationInfo().mEnterTransitionPostponed = true; 2367 } 2368 2369 /** 2370 * Begin postponed transitions after {@link #postponeEnterTransition()} was called. 2371 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition() 2372 * or {@link FragmentManager#executePendingTransactions()} to complete the FragmentTransaction. 2373 * If postponement was interrupted with {@link FragmentManager#executePendingTransactions()}, 2374 * before {@code startPostponedEnterTransition()}, animations may not run or may execute 2375 * improperly. 2376 * 2377 * @see Activity#startPostponedEnterTransition() 2378 */ 2379 public void startPostponedEnterTransition() { 2380 if (mFragmentManager == null || mFragmentManager.mHost == null) { 2381 ensureAnimationInfo().mEnterTransitionPostponed = false; 2382 } else if (Looper.myLooper() != mFragmentManager.mHost.getHandler().getLooper()) { 2383 mFragmentManager.mHost.getHandler(). 2384 postAtFrontOfQueue(this::callStartTransitionListener); 2385 } else { 2386 callStartTransitionListener(); 2387 } 2388 } 2389 2390 /** 2391 * Calls the start transition listener. This must be called on the UI thread. 2392 */ 2393 private void callStartTransitionListener() { 2394 final OnStartEnterTransitionListener listener; 2395 if (mAnimationInfo == null) { 2396 listener = null; 2397 } else { 2398 mAnimationInfo.mEnterTransitionPostponed = false; 2399 listener = mAnimationInfo.mStartEnterTransitionListener; 2400 mAnimationInfo.mStartEnterTransitionListener = null; 2401 } 2402 if (listener != null) { 2403 listener.onStartEnterTransition(); 2404 } 2405 } 2406 2407 /** 2408 * Returns true if mAnimationInfo is not null or the transition differs from the default value. 2409 * This is broken out to ensure mAnimationInfo is properly locked when checking. 2410 */ 2411 private boolean shouldChangeTransition(Transition transition, Transition defaultValue) { 2412 if (transition == defaultValue) { 2413 return mAnimationInfo != null; 2414 } 2415 return true; 2416 } 2417 2418 /** 2419 * Print the Fragments's state into the given stream. 2420 * 2421 * @param prefix Text to print at the front of each line. 2422 * @param fd The raw file descriptor that the dump is being sent to. 2423 * @param writer The PrintWriter to which you should dump your state. This will be 2424 * closed for you after you return. 2425 * @param args additional arguments to the dump request. 2426 */ 2427 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 2428 writer.print(prefix); writer.print("mFragmentId=#"); 2429 writer.print(Integer.toHexString(mFragmentId)); 2430 writer.print(" mContainerId=#"); 2431 writer.print(Integer.toHexString(mContainerId)); 2432 writer.print(" mTag="); writer.println(mTag); 2433 writer.print(prefix); writer.print("mState="); writer.print(mState); 2434 writer.print(" mIndex="); writer.print(mIndex); 2435 writer.print(" mWho="); writer.print(mWho); 2436 writer.print(" mBackStackNesting="); writer.println(mBackStackNesting); 2437 writer.print(prefix); writer.print("mAdded="); writer.print(mAdded); 2438 writer.print(" mRemoving="); writer.print(mRemoving); 2439 writer.print(" mFromLayout="); writer.print(mFromLayout); 2440 writer.print(" mInLayout="); writer.println(mInLayout); 2441 writer.print(prefix); writer.print("mHidden="); writer.print(mHidden); 2442 writer.print(" mDetached="); writer.print(mDetached); 2443 writer.print(" mMenuVisible="); writer.print(mMenuVisible); 2444 writer.print(" mHasMenu="); writer.println(mHasMenu); 2445 writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance); 2446 writer.print(" mRetaining="); writer.print(mRetaining); 2447 writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint); 2448 if (mFragmentManager != null) { 2449 writer.print(prefix); writer.print("mFragmentManager="); 2450 writer.println(mFragmentManager); 2451 } 2452 if (mHost != null) { 2453 writer.print(prefix); writer.print("mHost="); 2454 writer.println(mHost); 2455 } 2456 if (mParentFragment != null) { 2457 writer.print(prefix); writer.print("mParentFragment="); 2458 writer.println(mParentFragment); 2459 } 2460 if (mArguments != null) { 2461 writer.print(prefix); writer.print("mArguments="); writer.println(mArguments); 2462 } 2463 if (mSavedFragmentState != null) { 2464 writer.print(prefix); writer.print("mSavedFragmentState="); 2465 writer.println(mSavedFragmentState); 2466 } 2467 if (mSavedViewState != null) { 2468 writer.print(prefix); writer.print("mSavedViewState="); 2469 writer.println(mSavedViewState); 2470 } 2471 if (mTarget != null) { 2472 writer.print(prefix); writer.print("mTarget="); writer.print(mTarget); 2473 writer.print(" mTargetRequestCode="); 2474 writer.println(mTargetRequestCode); 2475 } 2476 if (getNextAnim() != 0) { 2477 writer.print(prefix); writer.print("mNextAnim="); writer.println(getNextAnim()); 2478 } 2479 if (mContainer != null) { 2480 writer.print(prefix); writer.print("mContainer="); writer.println(mContainer); 2481 } 2482 if (mView != null) { 2483 writer.print(prefix); writer.print("mView="); writer.println(mView); 2484 } 2485 if (getAnimatingAway() != null) { 2486 writer.print(prefix); writer.print("mAnimatingAway="); 2487 writer.println(getAnimatingAway()); 2488 writer.print(prefix); writer.print("mStateAfterAnimating="); 2489 writer.println(getStateAfterAnimating()); 2490 } 2491 if (mLoaderManager != null) { 2492 writer.print(prefix); writer.println("Loader Manager:"); 2493 mLoaderManager.dump(prefix + " ", fd, writer, args); 2494 } 2495 if (mChildFragmentManager != null) { 2496 writer.print(prefix); writer.println("Child " + mChildFragmentManager + ":"); 2497 mChildFragmentManager.dump(prefix + " ", fd, writer, args); 2498 } 2499 } 2500 2501 Fragment findFragmentByWho(String who) { 2502 if (who.equals(mWho)) { 2503 return this; 2504 } 2505 if (mChildFragmentManager != null) { 2506 return mChildFragmentManager.findFragmentByWho(who); 2507 } 2508 return null; 2509 } 2510 2511 void instantiateChildFragmentManager() { 2512 mChildFragmentManager = new FragmentManagerImpl(); 2513 mChildFragmentManager.attachController(mHost, new FragmentContainer() { 2514 @Override 2515 @Nullable 2516 public View onFindViewById(int id) { 2517 if (mView == null) { 2518 throw new IllegalStateException("Fragment does not have a view"); 2519 } 2520 return mView.findViewById(id); 2521 } 2522 2523 @Override 2524 public boolean onHasView() { 2525 return (mView != null); 2526 } 2527 }, this); 2528 } 2529 2530 void performCreate(Bundle savedInstanceState) { 2531 if (mChildFragmentManager != null) { 2532 mChildFragmentManager.noteStateNotSaved(); 2533 } 2534 mState = CREATED; 2535 mCalled = false; 2536 onCreate(savedInstanceState); 2537 if (!mCalled) { 2538 throw new SuperNotCalledException("Fragment " + this 2539 + " did not call through to super.onCreate()"); 2540 } 2541 final Context context = getContext(); 2542 final int version = context != null ? context.getApplicationInfo().targetSdkVersion : 0; 2543 if (version < Build.VERSION_CODES.N) { 2544 restoreChildFragmentState(savedInstanceState, false); 2545 } 2546 } 2547 2548 View performCreateView(LayoutInflater inflater, ViewGroup container, 2549 Bundle savedInstanceState) { 2550 if (mChildFragmentManager != null) { 2551 mChildFragmentManager.noteStateNotSaved(); 2552 } 2553 mPerformedCreateView = true; 2554 return onCreateView(inflater, container, savedInstanceState); 2555 } 2556 2557 void performActivityCreated(Bundle savedInstanceState) { 2558 if (mChildFragmentManager != null) { 2559 mChildFragmentManager.noteStateNotSaved(); 2560 } 2561 mState = ACTIVITY_CREATED; 2562 mCalled = false; 2563 onActivityCreated(savedInstanceState); 2564 if (!mCalled) { 2565 throw new SuperNotCalledException("Fragment " + this 2566 + " did not call through to super.onActivityCreated()"); 2567 } 2568 if (mChildFragmentManager != null) { 2569 mChildFragmentManager.dispatchActivityCreated(); 2570 } 2571 } 2572 2573 void performStart() { 2574 if (mChildFragmentManager != null) { 2575 mChildFragmentManager.noteStateNotSaved(); 2576 mChildFragmentManager.execPendingActions(); 2577 } 2578 mState = STARTED; 2579 mCalled = false; 2580 onStart(); 2581 if (!mCalled) { 2582 throw new SuperNotCalledException("Fragment " + this 2583 + " did not call through to super.onStart()"); 2584 } 2585 if (mChildFragmentManager != null) { 2586 mChildFragmentManager.dispatchStart(); 2587 } 2588 if (mLoaderManager != null) { 2589 mLoaderManager.doReportStart(); 2590 } 2591 } 2592 2593 void performResume() { 2594 if (mChildFragmentManager != null) { 2595 mChildFragmentManager.noteStateNotSaved(); 2596 mChildFragmentManager.execPendingActions(); 2597 } 2598 mState = RESUMED; 2599 mCalled = false; 2600 onResume(); 2601 if (!mCalled) { 2602 throw new SuperNotCalledException("Fragment " + this 2603 + " did not call through to super.onResume()"); 2604 } 2605 if (mChildFragmentManager != null) { 2606 mChildFragmentManager.dispatchResume(); 2607 mChildFragmentManager.execPendingActions(); 2608 } 2609 } 2610 2611 @Deprecated 2612 void performMultiWindowModeChanged(boolean isInMultiWindowMode) { 2613 onMultiWindowModeChanged(isInMultiWindowMode); 2614 if (mChildFragmentManager != null) { 2615 mChildFragmentManager.dispatchMultiWindowModeChanged(isInMultiWindowMode); 2616 } 2617 } 2618 2619 void performMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) { 2620 onMultiWindowModeChanged(isInMultiWindowMode, newConfig); 2621 if (mChildFragmentManager != null) { 2622 mChildFragmentManager.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig); 2623 } 2624 } 2625 2626 @Deprecated 2627 void performPictureInPictureModeChanged(boolean isInPictureInPictureMode) { 2628 onPictureInPictureModeChanged(isInPictureInPictureMode); 2629 if (mChildFragmentManager != null) { 2630 mChildFragmentManager.dispatchPictureInPictureModeChanged(isInPictureInPictureMode); 2631 } 2632 } 2633 2634 void performPictureInPictureModeChanged(boolean isInPictureInPictureMode, 2635 Configuration newConfig) { 2636 onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig); 2637 if (mChildFragmentManager != null) { 2638 mChildFragmentManager.dispatchPictureInPictureModeChanged(isInPictureInPictureMode, 2639 newConfig); 2640 } 2641 } 2642 2643 void performConfigurationChanged(Configuration newConfig) { 2644 onConfigurationChanged(newConfig); 2645 if (mChildFragmentManager != null) { 2646 mChildFragmentManager.dispatchConfigurationChanged(newConfig); 2647 } 2648 } 2649 2650 void performLowMemory() { 2651 onLowMemory(); 2652 if (mChildFragmentManager != null) { 2653 mChildFragmentManager.dispatchLowMemory(); 2654 } 2655 } 2656 2657 void performTrimMemory(int level) { 2658 onTrimMemory(level); 2659 if (mChildFragmentManager != null) { 2660 mChildFragmentManager.dispatchTrimMemory(level); 2661 } 2662 } 2663 2664 boolean performCreateOptionsMenu(Menu menu, MenuInflater inflater) { 2665 boolean show = false; 2666 if (!mHidden) { 2667 if (mHasMenu && mMenuVisible) { 2668 show = true; 2669 onCreateOptionsMenu(menu, inflater); 2670 } 2671 if (mChildFragmentManager != null) { 2672 show |= mChildFragmentManager.dispatchCreateOptionsMenu(menu, inflater); 2673 } 2674 } 2675 return show; 2676 } 2677 2678 boolean performPrepareOptionsMenu(Menu menu) { 2679 boolean show = false; 2680 if (!mHidden) { 2681 if (mHasMenu && mMenuVisible) { 2682 show = true; 2683 onPrepareOptionsMenu(menu); 2684 } 2685 if (mChildFragmentManager != null) { 2686 show |= mChildFragmentManager.dispatchPrepareOptionsMenu(menu); 2687 } 2688 } 2689 return show; 2690 } 2691 2692 boolean performOptionsItemSelected(MenuItem item) { 2693 if (!mHidden) { 2694 if (mHasMenu && mMenuVisible) { 2695 if (onOptionsItemSelected(item)) { 2696 return true; 2697 } 2698 } 2699 if (mChildFragmentManager != null) { 2700 if (mChildFragmentManager.dispatchOptionsItemSelected(item)) { 2701 return true; 2702 } 2703 } 2704 } 2705 return false; 2706 } 2707 2708 boolean performContextItemSelected(MenuItem item) { 2709 if (!mHidden) { 2710 if (onContextItemSelected(item)) { 2711 return true; 2712 } 2713 if (mChildFragmentManager != null) { 2714 if (mChildFragmentManager.dispatchContextItemSelected(item)) { 2715 return true; 2716 } 2717 } 2718 } 2719 return false; 2720 } 2721 2722 void performOptionsMenuClosed(Menu menu) { 2723 if (!mHidden) { 2724 if (mHasMenu && mMenuVisible) { 2725 onOptionsMenuClosed(menu); 2726 } 2727 if (mChildFragmentManager != null) { 2728 mChildFragmentManager.dispatchOptionsMenuClosed(menu); 2729 } 2730 } 2731 } 2732 2733 void performSaveInstanceState(Bundle outState) { 2734 onSaveInstanceState(outState); 2735 if (mChildFragmentManager != null) { 2736 Parcelable p = mChildFragmentManager.saveAllState(); 2737 if (p != null) { 2738 outState.putParcelable(Activity.FRAGMENTS_TAG, p); 2739 } 2740 } 2741 } 2742 2743 void performPause() { 2744 if (mChildFragmentManager != null) { 2745 mChildFragmentManager.dispatchPause(); 2746 } 2747 mState = STARTED; 2748 mCalled = false; 2749 onPause(); 2750 if (!mCalled) { 2751 throw new SuperNotCalledException("Fragment " + this 2752 + " did not call through to super.onPause()"); 2753 } 2754 } 2755 2756 void performStop() { 2757 if (mChildFragmentManager != null) { 2758 mChildFragmentManager.dispatchStop(); 2759 } 2760 mState = STOPPED; 2761 mCalled = false; 2762 onStop(); 2763 if (!mCalled) { 2764 throw new SuperNotCalledException("Fragment " + this 2765 + " did not call through to super.onStop()"); 2766 } 2767 2768 if (mLoadersStarted) { 2769 mLoadersStarted = false; 2770 if (!mCheckedForLoaderManager) { 2771 mCheckedForLoaderManager = true; 2772 mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false); 2773 } 2774 if (mLoaderManager != null) { 2775 if (mHost.getRetainLoaders()) { 2776 mLoaderManager.doRetain(); 2777 } else { 2778 mLoaderManager.doStop(); 2779 } 2780 } 2781 } 2782 } 2783 2784 void performDestroyView() { 2785 if (mChildFragmentManager != null) { 2786 mChildFragmentManager.dispatchDestroyView(); 2787 } 2788 mState = CREATED; 2789 mCalled = false; 2790 onDestroyView(); 2791 if (!mCalled) { 2792 throw new SuperNotCalledException("Fragment " + this 2793 + " did not call through to super.onDestroyView()"); 2794 } 2795 if (mLoaderManager != null) { 2796 mLoaderManager.doReportNextStart(); 2797 } 2798 mPerformedCreateView = false; 2799 } 2800 2801 void performDestroy() { 2802 if (mChildFragmentManager != null) { 2803 mChildFragmentManager.dispatchDestroy(); 2804 } 2805 mState = INITIALIZING; 2806 mCalled = false; 2807 onDestroy(); 2808 if (!mCalled) { 2809 throw new SuperNotCalledException("Fragment " + this 2810 + " did not call through to super.onDestroy()"); 2811 } 2812 mChildFragmentManager = null; 2813 } 2814 2815 void performDetach() { 2816 mCalled = false; 2817 onDetach(); 2818 if (!mCalled) { 2819 throw new SuperNotCalledException("Fragment " + this 2820 + " did not call through to super.onDetach()"); 2821 } 2822 2823 // Destroy the child FragmentManager if we still have it here. 2824 // We won't unless we're retaining our instance and if we do, 2825 // our child FragmentManager instance state will have already been saved. 2826 if (mChildFragmentManager != null) { 2827 if (!mRetaining) { 2828 throw new IllegalStateException("Child FragmentManager of " + this + " was not " 2829 + " destroyed and this fragment is not retaining instance"); 2830 } 2831 mChildFragmentManager.dispatchDestroy(); 2832 mChildFragmentManager = null; 2833 } 2834 } 2835 2836 void setOnStartEnterTransitionListener(OnStartEnterTransitionListener listener) { 2837 ensureAnimationInfo(); 2838 if (listener == mAnimationInfo.mStartEnterTransitionListener) { 2839 return; 2840 } 2841 if (listener != null && mAnimationInfo.mStartEnterTransitionListener != null) { 2842 throw new IllegalStateException("Trying to set a replacement " + 2843 "startPostponedEnterTransition on " + this); 2844 } 2845 if (mAnimationInfo.mEnterTransitionPostponed) { 2846 mAnimationInfo.mStartEnterTransitionListener = listener; 2847 } 2848 if (listener != null) { 2849 listener.startListening(); 2850 } 2851 } 2852 2853 private static Transition loadTransition(Context context, TypedArray typedArray, 2854 Transition currentValue, Transition defaultValue, int id) { 2855 if (currentValue != defaultValue) { 2856 return currentValue; 2857 } 2858 int transitionId = typedArray.getResourceId(id, 0); 2859 Transition transition = defaultValue; 2860 if (transitionId != 0 && transitionId != com.android.internal.R.transition.no_transition) { 2861 TransitionInflater inflater = TransitionInflater.from(context); 2862 transition = inflater.inflateTransition(transitionId); 2863 if (transition instanceof TransitionSet && 2864 ((TransitionSet)transition).getTransitionCount() == 0) { 2865 transition = null; 2866 } 2867 } 2868 return transition; 2869 } 2870 2871 private AnimationInfo ensureAnimationInfo() { 2872 if (mAnimationInfo == null) { 2873 mAnimationInfo = new AnimationInfo(); 2874 } 2875 return mAnimationInfo; 2876 } 2877 2878 int getNextAnim() { 2879 if (mAnimationInfo == null) { 2880 return 0; 2881 } 2882 return mAnimationInfo.mNextAnim; 2883 } 2884 2885 void setNextAnim(int animResourceId) { 2886 if (mAnimationInfo == null && animResourceId == 0) { 2887 return; // no change! 2888 } 2889 ensureAnimationInfo().mNextAnim = animResourceId; 2890 } 2891 2892 int getNextTransition() { 2893 if (mAnimationInfo == null) { 2894 return 0; 2895 } 2896 return mAnimationInfo.mNextTransition; 2897 } 2898 2899 void setNextTransition(int nextTransition, int nextTransitionStyle) { 2900 if (mAnimationInfo == null && nextTransition == 0 && nextTransitionStyle == 0) { 2901 return; // no change! 2902 } 2903 ensureAnimationInfo(); 2904 mAnimationInfo.mNextTransition = nextTransition; 2905 mAnimationInfo.mNextTransitionStyle = nextTransitionStyle; 2906 } 2907 2908 int getNextTransitionStyle() { 2909 if (mAnimationInfo == null) { 2910 return 0; 2911 } 2912 return mAnimationInfo.mNextTransitionStyle; 2913 } 2914 2915 SharedElementCallback getEnterTransitionCallback() { 2916 if (mAnimationInfo == null) { 2917 return SharedElementCallback.NULL_CALLBACK; 2918 } 2919 return mAnimationInfo.mEnterTransitionCallback; 2920 } 2921 2922 SharedElementCallback getExitTransitionCallback() { 2923 if (mAnimationInfo == null) { 2924 return SharedElementCallback.NULL_CALLBACK; 2925 } 2926 return mAnimationInfo.mExitTransitionCallback; 2927 } 2928 2929 Animator getAnimatingAway() { 2930 if (mAnimationInfo == null) { 2931 return null; 2932 } 2933 return mAnimationInfo.mAnimatingAway; 2934 } 2935 2936 void setAnimatingAway(Animator animator) { 2937 ensureAnimationInfo().mAnimatingAway = animator; 2938 } 2939 2940 int getStateAfterAnimating() { 2941 if (mAnimationInfo == null) { 2942 return 0; 2943 } 2944 return mAnimationInfo.mStateAfterAnimating; 2945 } 2946 2947 void setStateAfterAnimating(int state) { 2948 ensureAnimationInfo().mStateAfterAnimating = state; 2949 } 2950 2951 boolean isPostponed() { 2952 if (mAnimationInfo == null) { 2953 return false; 2954 } 2955 return mAnimationInfo.mEnterTransitionPostponed; 2956 } 2957 2958 boolean isHideReplaced() { 2959 if (mAnimationInfo == null) { 2960 return false; 2961 } 2962 return mAnimationInfo.mIsHideReplaced; 2963 } 2964 2965 void setHideReplaced(boolean replaced) { 2966 ensureAnimationInfo().mIsHideReplaced = replaced; 2967 } 2968 2969 /** 2970 * Used internally to be notified when {@link #startPostponedEnterTransition()} has 2971 * been called. This listener will only be called once and then be removed from the 2972 * listeners. 2973 */ 2974 interface OnStartEnterTransitionListener { 2975 void onStartEnterTransition(); 2976 void startListening(); 2977 } 2978 2979 /** 2980 * Contains all the animation and transition information for a fragment. This will only 2981 * be instantiated for Fragments that have Views. 2982 */ 2983 static class AnimationInfo { 2984 // Non-null if the fragment's view hierarchy is currently animating away, 2985 // meaning we need to wait a bit on completely destroying it. This is the 2986 // animation that is running. 2987 Animator mAnimatingAway; 2988 2989 // If mAnimatingAway != null, this is the state we should move to once the 2990 // animation is done. 2991 int mStateAfterAnimating; 2992 2993 // If app has requested a specific animation, this is the one to use. 2994 int mNextAnim; 2995 2996 // If app has requested a specific transition, this is the one to use. 2997 int mNextTransition; 2998 2999 // If app has requested a specific transition style, this is the one to use. 3000 int mNextTransitionStyle; 3001 3002 private Transition mEnterTransition = null; 3003 private Transition mReturnTransition = USE_DEFAULT_TRANSITION; 3004 private Transition mExitTransition = null; 3005 private Transition mReenterTransition = USE_DEFAULT_TRANSITION; 3006 private Transition mSharedElementEnterTransition = null; 3007 private Transition mSharedElementReturnTransition = USE_DEFAULT_TRANSITION; 3008 private Boolean mAllowReturnTransitionOverlap; 3009 private Boolean mAllowEnterTransitionOverlap; 3010 3011 SharedElementCallback mEnterTransitionCallback = SharedElementCallback.NULL_CALLBACK; 3012 SharedElementCallback mExitTransitionCallback = SharedElementCallback.NULL_CALLBACK; 3013 3014 // True when postponeEnterTransition has been called and startPostponeEnterTransition 3015 // hasn't been called yet. 3016 boolean mEnterTransitionPostponed; 3017 3018 // Listener to wait for startPostponeEnterTransition. After being called, it will 3019 // be set to null 3020 OnStartEnterTransitionListener mStartEnterTransitionListener; 3021 3022 // True if the View was hidden, but the transition is handling the hide 3023 boolean mIsHideReplaced; 3024 } 3025} 3026