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