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