1 /* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.app; 18 19 import android.animation.Animator; 20 import android.content.ComponentCallbacks2; 21 import android.content.Context; 22 import android.content.Intent; 23 import android.content.res.Configuration; 24 import android.content.res.Resources; 25 import android.os.Bundle; 26 import android.os.Parcel; 27 import android.os.Parcelable; 28 import android.util.AndroidRuntimeException; 29 import android.util.AttributeSet; 30 import android.util.DebugUtils; 31 import android.util.Log; 32 import android.util.SparseArray; 33 import android.view.ContextMenu; 34 import android.view.ContextMenu.ContextMenuInfo; 35 import android.view.LayoutInflater; 36 import android.view.Menu; 37 import android.view.MenuInflater; 38 import android.view.MenuItem; 39 import android.view.View; 40 import android.view.View.OnCreateContextMenuListener; 41 import android.view.ViewGroup; 42 import android.widget.AdapterView; 43 44 import java.io.FileDescriptor; 45 import java.io.PrintWriter; 46 import java.util.HashMap; 47 48 final class FragmentState implements Parcelable { 49 final String mClassName; 50 final int mIndex; 51 final boolean mFromLayout; 52 final int mFragmentId; 53 final int mContainerId; 54 final String mTag; 55 final boolean mRetainInstance; 56 final boolean mDetached; 57 final Bundle mArguments; 58 59 Bundle mSavedFragmentState; 60 61 Fragment mInstance; 62 63 public FragmentState(Fragment frag) { 64 mClassName = frag.getClass().getName(); 65 mIndex = frag.mIndex; 66 mFromLayout = frag.mFromLayout; 67 mFragmentId = frag.mFragmentId; 68 mContainerId = frag.mContainerId; 69 mTag = frag.mTag; 70 mRetainInstance = frag.mRetainInstance; 71 mDetached = frag.mDetached; 72 mArguments = frag.mArguments; 73 } 74 75 public FragmentState(Parcel in) { 76 mClassName = in.readString(); 77 mIndex = in.readInt(); 78 mFromLayout = in.readInt() != 0; 79 mFragmentId = in.readInt(); 80 mContainerId = in.readInt(); 81 mTag = in.readString(); 82 mRetainInstance = in.readInt() != 0; 83 mDetached = in.readInt() != 0; 84 mArguments = in.readBundle(); 85 mSavedFragmentState = in.readBundle(); 86 } 87 88 public Fragment instantiate(Activity activity, Fragment parent) { 89 if (mInstance != null) { 90 return mInstance; 91 } 92 93 if (mArguments != null) { 94 mArguments.setClassLoader(activity.getClassLoader()); 95 } 96 97 mInstance = Fragment.instantiate(activity, mClassName, mArguments); 98 99 if (mSavedFragmentState != null) { 100 mSavedFragmentState.setClassLoader(activity.getClassLoader()); 101 mInstance.mSavedFragmentState = mSavedFragmentState; 102 } 103 mInstance.setIndex(mIndex, parent); 104 mInstance.mFromLayout = mFromLayout; 105 mInstance.mRestored = true; 106 mInstance.mFragmentId = mFragmentId; 107 mInstance.mContainerId = mContainerId; 108 mInstance.mTag = mTag; 109 mInstance.mRetainInstance = mRetainInstance; 110 mInstance.mDetached = mDetached; 111 mInstance.mFragmentManager = activity.mFragments; 112 if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG, 113 "Instantiated fragment " + mInstance); 114 115 return mInstance; 116 } 117 118 public int describeContents() { 119 return 0; 120 } 121 122 public void writeToParcel(Parcel dest, int flags) { 123 dest.writeString(mClassName); 124 dest.writeInt(mIndex); 125 dest.writeInt(mFromLayout ? 1 : 0); 126 dest.writeInt(mFragmentId); 127 dest.writeInt(mContainerId); 128 dest.writeString(mTag); 129 dest.writeInt(mRetainInstance ? 1 : 0); 130 dest.writeInt(mDetached ? 1 : 0); 131 dest.writeBundle(mArguments); 132 dest.writeBundle(mSavedFragmentState); 133 } 134 135 public static final Parcelable.Creator<FragmentState> CREATOR 136 = new Parcelable.Creator<FragmentState>() { 137 public FragmentState createFromParcel(Parcel in) { 138 return new FragmentState(in); 139 } 140 141 public FragmentState[] newArray(int size) { 142 return new FragmentState[size]; 143 } 144 }; 145 } 146 147 /** 148 * A Fragment is a piece of an application's user interface or behavior 149 * that can be placed in an {@link Activity}. Interaction with fragments 150 * is done through {@link FragmentManager}, which can be obtained via 151 * {@link Activity#getFragmentManager() Activity.getFragmentManager()} and 152 * {@link Fragment#getFragmentManager() Fragment.getFragmentManager()}. 153 * 154 * <p>The Fragment class can be used many ways to achieve a wide variety of 155 * results. In its core, it represents a particular operation or interface 156 * that is running within a larger {@link Activity}. A Fragment is closely 157 * tied to the Activity it is in, and can not be used apart from one. Though 158 * Fragment defines its own lifecycle, that lifecycle is dependent on its 159 * activity: if the activity is stopped, no fragments inside of it can be 160 * started; when the activity is destroyed, all fragments will be destroyed. 161 * 162 * <p>All subclasses of Fragment must include a public empty constructor. 163 * The framework will often re-instantiate a fragment class when needed, 164 * in particular during state restore, and needs to be able to find this 165 * constructor to instantiate it. If the empty constructor is not available, 166 * a runtime exception will occur in some cases during state restore. 167 * 168 * <p>Topics covered here: 169 * <ol> 170 * <li><a href="#OlderPlatforms">Older Platforms</a> 171 * <li><a href="#Lifecycle">Lifecycle</a> 172 * <li><a href="#Layout">Layout</a> 173 * <li><a href="#BackStack">Back Stack</a> 174 * </ol> 175 * 176 * <div class="special reference"> 177 * <h3>Developer Guides</h3> 178 * <p>For more information about using fragments, read the 179 * <a href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</p> 180 * </div> 181 * 182 * <a name="OlderPlatforms"></a> 183 * <h3>Older Platforms</h3> 184 * 185 * While the Fragment API was introduced in 186 * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, a version of the API 187 * at is also available for use on older platforms through 188 * {@link android.support.v4.app.FragmentActivity}. See the blog post 189 * <a href="http://android-developers.blogspot.com/2011/03/fragments-for-all.html"> 190 * Fragments For All</a> for more details. 191 * 192 * <a name="Lifecycle"></a> 193 * <h3>Lifecycle</h3> 194 * 195 * <p>Though a Fragment's lifecycle is tied to its owning activity, it has 196 * its own wrinkle on the standard activity lifecycle. It includes basic 197 * activity lifecycle methods such as {@link #onResume}, but also important 198 * are methods related to interactions with the activity and UI generation. 199 * 200 * <p>The core series of lifecycle methods that are called to bring a fragment 201 * up to resumed state (interacting with the user) are: 202 * 203 * <ol> 204 * <li> {@link #onAttach} called once the fragment is associated with its activity. 205 * <li> {@link #onCreate} called to do initial creation of the fragment. 206 * <li> {@link #onCreateView} creates and returns the view hierarchy associated 207 * with the fragment. 208 * <li> {@link #onActivityCreated} tells the fragment that its activity has 209 * completed its own {@link Activity#onCreate Activity.onCreate()}. 210 * <li> {@link #onViewStateRestored} tells the fragment that all of the saved 211 * state of its view hierarchy has been restored. 212 * <li> {@link #onStart} makes the fragment visible to the user (based on its 213 * containing activity being started). 214 * <li> {@link #onResume} makes the fragment interacting with the user (based on its 215 * containing activity being resumed). 216 * </ol> 217 * 218 * <p>As a fragment is no longer being used, it goes through a reverse 219 * series of callbacks: 220 * 221 * <ol> 222 * <li> {@link #onPause} fragment is no longer interacting with the user either 223 * because its activity is being paused or a fragment operation is modifying it 224 * in the activity. 225 * <li> {@link #onStop} fragment is no longer visible to the user either 226 * because its activity is being stopped or a fragment operation is modifying it 227 * in the activity. 228 * <li> {@link #onDestroyView} allows the fragment to clean up resources 229 * associated with its View. 230 * <li> {@link #onDestroy} called to do final cleanup of the fragment's state. 231 * <li> {@link #onDetach} called immediately prior to the fragment no longer 232 * being associated with its activity. 233 * </ol> 234 * 235 * <a name="Layout"></a> 236 * <h3>Layout</h3> 237 * 238 * <p>Fragments can be used as part of your application's layout, allowing 239 * you to better modularize your code and more easily adjust your user 240 * interface to the screen it is running on. As an example, we can look 241 * at a simple program consisting of a list of items, and display of the 242 * details of each item.</p> 243 * 244 * <p>An activity's layout XML can include <code><fragment></code> tags 245 * to embed fragment instances inside of the layout. For example, here is 246 * a simple layout that embeds one fragment:</p> 247 * 248 * {@sample development/samples/ApiDemos/res/layout/fragment_layout.xml layout} 249 * 250 * <p>The layout is installed in the activity in the normal way:</p> 251 * 252 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java 253 * main} 254 * 255 * <p>The titles fragment, showing a list of titles, is fairly simple, relying 256 * on {@link ListFragment} for most of its work. Note the implementation of 257 * clicking an item: depending on the current activity's layout, it can either 258 * create and display a new fragment to show the details in-place (more about 259 * this later), or start a new activity to show the details.</p> 260 * 261 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java 262 * titles} 263 * 264 * <p>The details fragment showing the contents of a selected item just 265 * displays a string of text based on an index of a string array built in to 266 * the app:</p> 267 * 268 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java 269 * details} 270 * 271 * <p>In this case when the user clicks on a title, there is no details 272 * container in the current activity, so the titles fragment's click code will 273 * launch a new activity to display the details fragment:</p> 274 * 275 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.java 276 * details_activity} 277 * 278 * <p>However the screen may be large enough to show both the list of titles 279 * and details about the currently selected title. To use such a layout on 280 * a landscape screen, this alternative layout can be placed under layout-land:</p> 281 * 282 * {@sample development/samples/ApiDemos/res/layout-land/fragment_layout.xml layout} 283 * 284 * <p>Note how the prior code will adjust to this alternative UI flow: the titles 285 * fragment will now embed the details fragment inside of this activity, and the 286 * details activity will finish itself if it is running in a configuration 287 * where the details can be shown in-place. 288 * 289 * <p>When a configuration change causes the activity hosting these fragments 290 * to restart, its new instance may use a different layout that doesn't 291 * include the same fragments as the previous layout. In this case all of 292 * the previous fragments will still be instantiated and running in the new 293 * instance. However, any that are no longer associated with a <fragment> 294 * tag in the view hierarchy will not have their content view created 295 * and will return false from {@link #isInLayout}. (The code here also shows 296 * how you can determine if a fragment placed in a container is no longer 297 * running in a layout with that container and avoid creating its view hierarchy 298 * in that case.) 299 * 300 * <p>The attributes of the <fragment> tag are used to control the 301 * LayoutParams provided when attaching the fragment's view to the parent 302 * container. They can also be parsed by the fragment in {@link #onInflate} 303 * as parameters. 304 * 305 * <p>The fragment being instantiated must have some kind of unique identifier 306 * so that it can be re-associated with a previous instance if the parent 307 * activity needs to be destroyed and recreated. This can be provided these 308 * ways: 309 * 310 * <ul> 311 * <li>If nothing is explicitly supplied, the view ID of the container will 312 * be used. 313 * <li><code>android:tag</code> can be used in <fragment> to provide 314 * a specific tag name for the fragment. 315 * <li><code>android:id</code> can be used in <fragment> to provide 316 * a specific identifier for the fragment. 317 * </ul> 318 * 319 * <a name="BackStack"></a> 320 * <h3>Back Stack</h3> 321 * 322 * <p>The transaction in which fragments are modified can be placed on an 323 * internal back-stack of the owning activity. When the user presses back 324 * in the activity, any transactions on the back stack are popped off before 325 * the activity itself is finished. 326 * 327 * <p>For example, consider this simple fragment that is instantiated with 328 * an integer argument and displays that in a TextView in its UI:</p> 329 * 330 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java 331 * fragment} 332 * 333 * <p>A function that creates a new instance of the fragment, replacing 334 * whatever current fragment instance is being shown and pushing that change 335 * on to the back stack could be written as: 336 * 337 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentStack.java 338 * add_stack} 339 * 340 * <p>After each call to this function, a new entry is on the stack, and 341 * pressing back will pop it to return the user to whatever previous state 342 * the activity UI was in. 343 */ 344 public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListener { 345 private static final HashMap<String, Class<?>> sClassMap = 346 new HashMap<String, Class<?>>(); 347 348 static final int INVALID_STATE = -1; // Invalid state used as a null value. 349 static final int INITIALIZING = 0; // Not yet created. 350 static final int CREATED = 1; // Created. 351 static final int ACTIVITY_CREATED = 2; // The activity has finished its creation. 352 static final int STOPPED = 3; // Fully created, not started. 353 static final int STARTED = 4; // Created and started, not resumed. 354 static final int RESUMED = 5; // Created started and resumed. 355 356 int mState = INITIALIZING; 357 358 // Non-null if the fragment's view hierarchy is currently animating away, 359 // meaning we need to wait a bit on completely destroying it. This is the 360 // animation that is running. 361 Animator mAnimatingAway; 362 363 // If mAnimatingAway != null, this is the state we should move to once the 364 // animation is done. 365 int mStateAfterAnimating; 366 367 // When instantiated from saved state, this is the saved state. 368 Bundle mSavedFragmentState; 369 SparseArray<Parcelable> mSavedViewState; 370 371 // Index into active fragment array. 372 int mIndex = -1; 373 374 // Internal unique name for this fragment; 375 String mWho; 376 377 // Construction arguments; 378 Bundle mArguments; 379 380 // Target fragment. 381 Fragment mTarget; 382 383 // For use when retaining a fragment: this is the index of the last mTarget. 384 int mTargetIndex = -1; 385 386 // Target request code. 387 int mTargetRequestCode; 388 389 // True if the fragment is in the list of added fragments. 390 boolean mAdded; 391 392 // If set this fragment is being removed from its activity. 393 boolean mRemoving; 394 395 // True if the fragment is in the resumed state. 396 boolean mResumed; 397 398 // Set to true if this fragment was instantiated from a layout file. 399 boolean mFromLayout; 400 401 // Set to true when the view has actually been inflated in its layout. 402 boolean mInLayout; 403 404 // True if this fragment has been restored from previously saved state. 405 boolean mRestored; 406 407 // Number of active back stack entries this fragment is in. 408 int mBackStackNesting; 409 410 // The fragment manager we are associated with. Set as soon as the 411 // fragment is used in a transaction; cleared after it has been removed 412 // from all transactions. 413 FragmentManagerImpl mFragmentManager; 414 415 // Activity this fragment is attached to. 416 Activity mActivity; 417 418 // Private fragment manager for child fragments inside of this one. 419 FragmentManagerImpl mChildFragmentManager; 420 421 // If this Fragment is contained in another Fragment, this is that container. 422 Fragment mParentFragment; 423 424 // The optional identifier for this fragment -- either the container ID if it 425 // was dynamically added to the view hierarchy, or the ID supplied in 426 // layout. 427 int mFragmentId; 428 429 // When a fragment is being dynamically added to the view hierarchy, this 430 // is the identifier of the parent container it is being added to. 431 int mContainerId; 432 433 // The optional named tag for this fragment -- usually used to find 434 // fragments that are not part of the layout. 435 String mTag; 436 437 // Set to true when the app has requested that this fragment be hidden 438 // from the user. 439 boolean mHidden; 440 441 // Set to true when the app has requested that this fragment be detached. 442 boolean mDetached; 443 444 // If set this fragment would like its instance retained across 445 // configuration changes. 446 boolean mRetainInstance; 447 448 // If set this fragment is being retained across the current config change. 449 boolean mRetaining; 450 451 // If set this fragment has menu items to contribute. 452 boolean mHasMenu; 453 454 // Set to true to allow the fragment's menu to be shown. 455 boolean mMenuVisible = true; 456 457 // Used to verify that subclasses call through to super class. 458 boolean mCalled; 459 460 // If app has requested a specific animation, this is the one to use. 461 int mNextAnim; 462 463 // The parent container of the fragment after dynamically added to UI. 464 ViewGroup mContainer; 465 466 // The View generated for this fragment. 467 View mView; 468 469 // Whether this fragment should defer starting until after other fragments 470 // have been started and their loaders are finished. 471 boolean mDeferStart; 472 473 // Hint provided by the app that this fragment is currently visible to the user. 474 boolean mUserVisibleHint = true; 475 476 LoaderManagerImpl mLoaderManager; 477 boolean mLoadersStarted; 478 boolean mCheckedForLoaderManager; 479 480 /** 481 * State information that has been retrieved from a fragment instance 482 * through {@link FragmentManager#saveFragmentInstanceState(Fragment) 483 * FragmentManager.saveFragmentInstanceState}. 484 */ 485 public static class SavedState implements Parcelable { 486 final Bundle mState; 487 488 SavedState(Bundle state) { 489 mState = state; 490 } 491 492 SavedState(Parcel in, ClassLoader loader) { 493 mState = in.readBundle(); 494 if (loader != null && mState != null) { 495 mState.setClassLoader(loader); 496 } 497 } 498 499 @Override 500 public int describeContents() { 501 return 0; 502 } 503 504 @Override 505 public void writeToParcel(Parcel dest, int flags) { 506 dest.writeBundle(mState); 507 } 508 509 public static final Parcelable.ClassLoaderCreator<SavedState> CREATOR 510 = new Parcelable.ClassLoaderCreator<SavedState>() { 511 public SavedState createFromParcel(Parcel in) { 512 return new SavedState(in, null); 513 } 514 515 public SavedState createFromParcel(Parcel in, ClassLoader loader) { 516 return new SavedState(in, loader); 517 } 518 519 public SavedState[] newArray(int size) { 520 return new SavedState[size]; 521 } 522 }; 523 } 524 525 /** 526 * Thrown by {@link Fragment#instantiate(Context, String, Bundle)} when 527 * there is an instantiation failure. 528 */ 529 static public class InstantiationException extends AndroidRuntimeException { 530 public InstantiationException(String msg, Exception cause) { 531 super(msg, cause); 532 } 533 } 534 535 /** 536 * Default constructor. <strong>Every</strong> fragment must have an 537 * empty constructor, so it can be instantiated when restoring its 538 * activity's state. It is strongly recommended that subclasses do not 539 * have other constructors with parameters, since these constructors 540 * will not be called when the fragment is re-instantiated; instead, 541 * arguments can be supplied by the caller with {@link #setArguments} 542 * and later retrieved by the Fragment with {@link #getArguments}. 543 * 544 * <p>Applications should generally not implement a constructor. The 545 * first place application code an run where the fragment is ready to 546 * be used is in {@link #onAttach(Activity)}, the point where the fragment 547 * is actually associated with its activity. Some applications may also 548 * want to implement {@link #onInflate} to retrieve attributes from a 549 * layout resource, though should take care here because this happens for 550 * the fragment is attached to its activity. 551 */ 552 public Fragment() { 553 } 554 555 /** 556 * Like {@link #instantiate(Context, String, Bundle)} but with a null 557 * argument Bundle. 558 */ 559 public static Fragment instantiate(Context context, String fname) { 560 return instantiate(context, fname, null); 561 } 562 563 /** 564 * Create a new instance of a Fragment with the given class name. This is 565 * the same as calling its empty constructor. 566 * 567 * @param context The calling context being used to instantiate the fragment. 568 * This is currently just used to get its ClassLoader. 569 * @param fname The class name of the fragment to instantiate. 570 * @param args Bundle of arguments to supply to the fragment, which it 571 * can retrieve with {@link #getArguments()}. May be null. 572 * @return Returns a new fragment instance. 573 * @throws InstantiationException If there is a failure in instantiating 574 * the given fragment class. This is a runtime exception; it is not 575 * normally expected to happen. 576 */ 577 public static Fragment instantiate(Context context, String fname, Bundle args) { 578 try { 579 Class<?> clazz = sClassMap.get(fname); 580 if (clazz == null) { 581 // Class not found in the cache, see if it's real, and try to add it 582 clazz = context.getClassLoader().loadClass(fname); 583 sClassMap.put(fname, clazz); 584 } 585 Fragment f = (Fragment)clazz.newInstance(); 586 if (args != null) { 587 args.setClassLoader(f.getClass().getClassLoader()); 588 f.mArguments = args; 589 } 590 return f; 591 } catch (ClassNotFoundException e) { 592 throw new InstantiationException("Unable to instantiate fragment " + fname 593 + ": make sure class name exists, is public, and has an" 594 + " empty constructor that is public", e); 595 } catch (java.lang.InstantiationException e) { 596 throw new InstantiationException("Unable to instantiate fragment " + fname 597 + ": make sure class name exists, is public, and has an" 598 + " empty constructor that is public", e); 599 } catch (IllegalAccessException e) { 600 throw new InstantiationException("Unable to instantiate fragment " + fname 601 + ": make sure class name exists, is public, and has an" 602 + " empty constructor that is public", e); 603 } 604 } 605 606 final void restoreViewState(Bundle savedInstanceState) { 607 if (mSavedViewState != null) { 608 mView.restoreHierarchyState(mSavedViewState); 609 mSavedViewState = null; 610 } 611 mCalled = false; 612 onViewStateRestored(savedInstanceState); 613 if (!mCalled) { 614 throw new SuperNotCalledException("Fragment " + this 615 + " did not call through to super.onViewStateRestored()"); 616 } 617 } 618 619 final void setIndex(int index, Fragment parent) { 620 mIndex = index; 621 if (parent != null) { 622 mWho = parent.mWho + ":" + mIndex; 623 } else { 624 mWho = "android:fragment:" + mIndex; 625 } 626 } 627 628 final boolean isInBackStack() { 629 return mBackStackNesting > 0; 630 } 631 632 /** 633 * Subclasses can not override equals(). 634 */ 635 @Override final public boolean equals(Object o) { 636 return super.equals(o); 637 } 638 639 /** 640 * Subclasses can not override hashCode(). 641 */ 642 @Override final public int hashCode() { 643 return super.hashCode(); 644 } 645 646 @Override 647 public String toString() { 648 StringBuilder sb = new StringBuilder(128); 649 DebugUtils.buildShortClassTag(this, sb); 650 if (mIndex >= 0) { 651 sb.append(" #"); 652 sb.append(mIndex); 653 } 654 if (mFragmentId != 0) { 655 sb.append(" id=0x"); 656 sb.append(Integer.toHexString(mFragmentId)); 657 } 658 if (mTag != null) { 659 sb.append(" "); 660 sb.append(mTag); 661 } 662 sb.append('}'); 663 return sb.toString(); 664 } 665 666 /** 667 * Return the identifier this fragment is known by. This is either 668 * the android:id value supplied in a layout or the container view ID 669 * supplied when adding the fragment. 670 */ 671 final public int getId() { 672 return mFragmentId; 673 } 674 675 /** 676 * Get the tag name of the fragment, if specified. 677 */ 678 final public String getTag() { 679 return mTag; 680 } 681 682 /** 683 * Supply the construction arguments for this fragment. This can only 684 * be called before the fragment has been attached to its activity; that 685 * is, you should call it immediately after constructing the fragment. The 686 * arguments supplied here will be retained across fragment destroy and 687 * creation. 688 */ 689 public void setArguments(Bundle args) { 690 if (mIndex >= 0) { 691 throw new IllegalStateException("Fragment already active"); 692 } 693 mArguments = args; 694 } 695 696 /** 697 * Return the arguments supplied when the fragment was instantiated, 698 * if any. 699 */ 700 final public Bundle getArguments() { 701 return mArguments; 702 } 703 704 /** 705 * Set the initial saved state that this Fragment should restore itself 706 * from when first being constructed, as returned by 707 * {@link FragmentManager#saveFragmentInstanceState(Fragment) 708 * FragmentManager.saveFragmentInstanceState}. 709 * 710 * @param state The state the fragment should be restored from. 711 */ 712 public void setInitialSavedState(SavedState state) { 713 if (mIndex >= 0) { 714 throw new IllegalStateException("Fragment already active"); 715 } 716 mSavedFragmentState = state != null && state.mState != null 717 ? state.mState : null; 718 } 719 720 /** 721 * Optional target for this fragment. This may be used, for example, 722 * if this fragment is being started by another, and when done wants to 723 * give a result back to the first. The target set here is retained 724 * across instances via {@link FragmentManager#putFragment 725 * FragmentManager.putFragment()}. 726 * 727 * @param fragment The fragment that is the target of this one. 728 * @param requestCode Optional request code, for convenience if you 729 * are going to call back with {@link #onActivityResult(int, int, Intent)}. 730 */ 731 public void setTargetFragment(Fragment fragment, int requestCode) { 732 mTarget = fragment; 733 mTargetRequestCode = requestCode; 734 } 735 736 /** 737 * Return the target fragment set by {@link #setTargetFragment}. 738 */ 739 final public Fragment getTargetFragment() { 740 return mTarget; 741 } 742 743 /** 744 * Return the target request code set by {@link #setTargetFragment}. 745 */ 746 final public int getTargetRequestCode() { 747 return mTargetRequestCode; 748 } 749 750 /** 751 * Return the Activity this fragment is currently associated with. 752 */ 753 final public Activity getActivity() { 754 return mActivity; 755 } 756 757 /** 758 * Return <code>getActivity().getResources()</code>. 759 */ 760 final public Resources getResources() { 761 if (mActivity == null) { 762 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 763 } 764 return mActivity.getResources(); 765 } 766 767 /** 768 * Return a localized, styled CharSequence from the application's package's 769 * default string table. 770 * 771 * @param resId Resource id for the CharSequence text 772 */ 773 public final CharSequence getText(int resId) { 774 return getResources().getText(resId); 775 } 776 777 /** 778 * Return a localized string from the application's package's 779 * default string table. 780 * 781 * @param resId Resource id for the string 782 */ 783 public final String getString(int resId) { 784 return getResources().getString(resId); 785 } 786 787 /** 788 * Return a localized formatted string from the application's package's 789 * default string table, substituting the format arguments as defined in 790 * {@link java.util.Formatter} and {@link java.lang.String#format}. 791 * 792 * @param resId Resource id for the format string 793 * @param formatArgs The format arguments that will be used for substitution. 794 */ 795 796 public final String getString(int resId, Object... formatArgs) { 797 return getResources().getString(resId, formatArgs); 798 } 799 800 /** 801 * Return the FragmentManager for interacting with fragments associated 802 * with this fragment's activity. Note that this will be non-null slightly 803 * before {@link #getActivity()}, during the time from when the fragment is 804 * placed in a {@link FragmentTransaction} until it is committed and 805 * attached to its activity. 806 * 807 * <p>If this Fragment is a child of another Fragment, the FragmentManager 808 * returned here will be the parent's {@link #getChildFragmentManager()}. 809 */ 810 final public FragmentManager getFragmentManager() { 811 return mFragmentManager; 812 } 813 814 /** 815 * Return a private FragmentManager for placing and managing Fragments 816 * inside of this Fragment. 817 */ 818 final public FragmentManager getChildFragmentManager() { 819 if (mChildFragmentManager == null) { 820 instantiateChildFragmentManager(); 821 if (mState >= RESUMED) { 822 mChildFragmentManager.dispatchResume(); 823 } else if (mState >= STARTED) { 824 mChildFragmentManager.dispatchStart(); 825 } else if (mState >= ACTIVITY_CREATED) { 826 mChildFragmentManager.dispatchActivityCreated(); 827 } else if (mState >= CREATED) { 828 mChildFragmentManager.dispatchCreate(); 829 } 830 } 831 return mChildFragmentManager; 832 } 833 834 /** 835 * Returns the parent Fragment containing this Fragment. If this Fragment 836 * is attached directly to an Activity, returns null. 837 */ 838 final public Fragment getParentFragment() { 839 return mParentFragment; 840 } 841 842 /** 843 * Return true if the fragment is currently added to its activity. 844 */ 845 final public boolean isAdded() { 846 return mActivity != null && mAdded; 847 } 848 849 /** 850 * Return true if the fragment has been explicitly detached from the UI. 851 * That is, {@link FragmentTransaction#detach(Fragment) 852 * FragmentTransaction.detach(Fragment)} has been used on it. 853 */ 854 final public boolean isDetached() { 855 return mDetached; 856 } 857 858 /** 859 * Return true if this fragment is currently being removed from its 860 * activity. This is <em>not</em> whether its activity is finishing, but 861 * rather whether it is in the process of being removed from its activity. 862 */ 863 final public boolean isRemoving() { 864 return mRemoving; 865 } 866 867 /** 868 * Return true if the layout is included as part of an activity view 869 * hierarchy via the <fragment> tag. This will always be true when 870 * fragments are created through the <fragment> tag, <em>except</em> 871 * in the case where an old fragment is restored from a previous state and 872 * it does not appear in the layout of the current state. 873 */ 874 final public boolean isInLayout() { 875 return mInLayout; 876 } 877 878 /** 879 * Return true if the fragment is in the resumed state. This is true 880 * for the duration of {@link #onResume()} and {@link #onPause()} as well. 881 */ 882 final public boolean isResumed() { 883 return mResumed; 884 } 885 886 /** 887 * Return true if the fragment is currently visible to the user. This means 888 * it: (1) has been added, (2) has its view attached to the window, and 889 * (3) is not hidden. 890 */ 891 final public boolean isVisible() { 892 return isAdded() && !isHidden() && mView != null 893 && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE; 894 } 895 896 /** 897 * Return true if the fragment has been hidden. By default fragments 898 * are shown. You can find out about changes to this state with 899 * {@link #onHiddenChanged}. Note that the hidden state is orthogonal 900 * to other states -- that is, to be visible to the user, a fragment 901 * must be both started and not hidden. 902 */ 903 final public boolean isHidden() { 904 return mHidden; 905 } 906 907 /** 908 * Called when the hidden state (as returned by {@link #isHidden()} of 909 * the fragment has changed. Fragments start out not hidden; this will 910 * be called whenever the fragment changes state from that. 911 * @param hidden True if the fragment is now hidden, false if it is not 912 * visible. 913 */ 914 public void onHiddenChanged(boolean hidden) { 915 } 916 917 /** 918 * Control whether a fragment instance is retained across Activity 919 * re-creation (such as from a configuration change). This can only 920 * be used with fragments not in the back stack. If set, the fragment 921 * lifecycle will be slightly different when an activity is recreated: 922 * <ul> 923 * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still 924 * will be, because the fragment is being detached from its current activity). 925 * <li> {@link #onCreate(Bundle)} will not be called since the fragment 926 * is not being re-created. 927 * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b> 928 * still be called. 929 * </ul> 930 */ 931 public void setRetainInstance(boolean retain) { 932 if (retain && mParentFragment != null) { 933 throw new IllegalStateException( 934 "Can't retain fragements that are nested in other fragments"); 935 } 936 mRetainInstance = retain; 937 } 938 939 final public boolean getRetainInstance() { 940 return mRetainInstance; 941 } 942 943 /** 944 * Report that this fragment would like to participate in populating 945 * the options menu by receiving a call to {@link #onCreateOptionsMenu} 946 * and related methods. 947 * 948 * @param hasMenu If true, the fragment has menu items to contribute. 949 */ 950 public void setHasOptionsMenu(boolean hasMenu) { 951 if (mHasMenu != hasMenu) { 952 mHasMenu = hasMenu; 953 if (isAdded() && !isHidden()) { 954 mFragmentManager.invalidateOptionsMenu(); 955 } 956 } 957 } 958 959 /** 960 * Set a hint for whether this fragment's menu should be visible. This 961 * is useful if you know that a fragment has been placed in your view 962 * hierarchy so that the user can not currently seen it, so any menu items 963 * it has should also not be shown. 964 * 965 * @param menuVisible The default is true, meaning the fragment's menu will 966 * be shown as usual. If false, the user will not see the menu. 967 */ 968 public void setMenuVisibility(boolean menuVisible) { 969 if (mMenuVisible != menuVisible) { 970 mMenuVisible = menuVisible; 971 if (mHasMenu && isAdded() && !isHidden()) { 972 mFragmentManager.invalidateOptionsMenu(); 973 } 974 } 975 } 976 977 /** 978 * Set a hint to the system about whether this fragment's UI is currently visible 979 * to the user. This hint defaults to true and is persistent across fragment instance 980 * state save and restore. 981 * 982 * <p>An app may set this to false to indicate that the fragment's UI is 983 * scrolled out of visibility or is otherwise not directly visible to the user. 984 * This may be used by the system to prioritize operations such as fragment lifecycle updates 985 * or loader ordering behavior.</p> 986 * 987 * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default), 988 * false if it is not. 989 */ 990 public void setUserVisibleHint(boolean isVisibleToUser) { 991 if (!mUserVisibleHint && isVisibleToUser && mState < STARTED) { 992 mFragmentManager.performPendingDeferredStart(this); 993 } 994 mUserVisibleHint = isVisibleToUser; 995 mDeferStart = !isVisibleToUser; 996 } 997 998 /** 999 * @return The current value of the user-visible hint on this fragment. 1000 * @see #setUserVisibleHint(boolean) 1001 */ 1002 public boolean getUserVisibleHint() { 1003 return mUserVisibleHint; 1004 } 1005 1006 /** 1007 * Return the LoaderManager for this fragment, creating it if needed. 1008 */ 1009 public LoaderManager getLoaderManager() { 1010 if (mLoaderManager != null) { 1011 return mLoaderManager; 1012 } 1013 if (mActivity == null) { 1014 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 1015 } 1016 mCheckedForLoaderManager = true; 1017 mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, true); 1018 return mLoaderManager; 1019 } 1020 1021 /** 1022 * Call {@link Activity#startActivity(Intent)} on the fragment's 1023 * containing Activity. 1024 * 1025 * @param intent The intent to start. 1026 */ 1027 public void startActivity(Intent intent) { 1028 startActivity(intent, null); 1029 } 1030 1031 /** 1032 * Call {@link Activity#startActivity(Intent, Bundle)} on the fragment's 1033 * containing Activity. 1034 * 1035 * @param intent The intent to start. 1036 * @param options Additional options for how the Activity should be started. 1037 * See {@link android.content.Context#startActivity(Intent, Bundle) 1038 * Context.startActivity(Intent, Bundle)} for more details. 1039 */ 1040 public void startActivity(Intent intent, Bundle options) { 1041 if (mActivity == null) { 1042 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 1043 } 1044 if (options != null) { 1045 mActivity.startActivityFromFragment(this, intent, -1, options); 1046 } else { 1047 // Note we want to go through this call for compatibility with 1048 // applications that may have overridden the method. 1049 mActivity.startActivityFromFragment(this, intent, -1); 1050 } 1051 } 1052 1053 /** 1054 * Call {@link Activity#startActivityForResult(Intent, int)} on the fragment's 1055 * containing Activity. 1056 */ 1057 public void startActivityForResult(Intent intent, int requestCode) { 1058 startActivityForResult(intent, requestCode, null); 1059 } 1060 1061 /** 1062 * Call {@link Activity#startActivityForResult(Intent, int, Bundle)} on the fragment's 1063 * containing Activity. 1064 */ 1065 public void startActivityForResult(Intent intent, int requestCode, Bundle options) { 1066 if (mActivity == null) { 1067 throw new IllegalStateException("Fragment " + this + " not attached to Activity"); 1068 } 1069 if (options != null) { 1070 mActivity.startActivityFromFragment(this, intent, requestCode, options); 1071 } else { 1072 // Note we want to go through this call for compatibility with 1073 // applications that may have overridden the method. 1074 mActivity.startActivityFromFragment(this, intent, requestCode, options); 1075 } 1076 } 1077 1078 /** 1079 * Receive the result from a previous call to 1080 * {@link #startActivityForResult(Intent, int)}. This follows the 1081 * related Activity API as described there in 1082 * {@link Activity#onActivityResult(int, int, Intent)}. 1083 * 1084 * @param requestCode The integer request code originally supplied to 1085 * startActivityForResult(), allowing you to identify who this 1086 * result came from. 1087 * @param resultCode The integer result code returned by the child activity 1088 * through its setResult(). 1089 * @param data An Intent, which can return result data to the caller 1090 * (various data can be attached to Intent "extras"). 1091 */ 1092 public void onActivityResult(int requestCode, int resultCode, Intent data) { 1093 } 1094 1095 /** 1096 * @hide Hack so that DialogFragment can make its Dialog before creating 1097 * its views, and the view construction can use the dialog's context for 1098 * inflation. Maybe this should become a public API. Note sure. 1099 */ 1100 public LayoutInflater getLayoutInflater(Bundle savedInstanceState) { 1101 return mActivity.getLayoutInflater(); 1102 } 1103 1104 /** 1105 * @deprecated Use {@link #onInflate(Activity, AttributeSet, Bundle)} instead. 1106 */ 1107 @Deprecated 1108 public void onInflate(AttributeSet attrs, Bundle savedInstanceState) { 1109 mCalled = true; 1110 } 1111 1112 /** 1113 * Called when a fragment is being created as part of a view layout 1114 * inflation, typically from setting the content view of an activity. This 1115 * may be called immediately after the fragment is created from a <fragment> 1116 * tag in a layout file. Note this is <em>before</em> the fragment's 1117 * {@link #onAttach(Activity)} has been called; all you should do here is 1118 * parse the attributes and save them away. 1119 * 1120 * <p>This is called every time the fragment is inflated, even if it is 1121 * being inflated into a new instance with saved state. It typically makes 1122 * sense to re-parse the parameters each time, to allow them to change with 1123 * different configurations.</p> 1124 * 1125 * <p>Here is a typical implementation of a fragment that can take parameters 1126 * both through attributes supplied here as well from {@link #getArguments()}:</p> 1127 * 1128 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java 1129 * fragment} 1130 * 1131 * <p>Note that parsing the XML attributes uses a "styleable" resource. The 1132 * declaration for the styleable used here is:</p> 1133 * 1134 * {@sample development/samples/ApiDemos/res/values/attrs.xml fragment_arguments} 1135 * 1136 * <p>The fragment can then be declared within its activity's content layout 1137 * through a tag like this:</p> 1138 * 1139 * {@sample development/samples/ApiDemos/res/layout/fragment_arguments.xml from_attributes} 1140 * 1141 * <p>This fragment can also be created dynamically from arguments given 1142 * at runtime in the arguments Bundle; here is an example of doing so at 1143 * creation of the containing activity:</p> 1144 * 1145 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java 1146 * create} 1147 * 1148 * @param activity The Activity that is inflating this fragment. 1149 * @param attrs The attributes at the tag where the fragment is 1150 * being created. 1151 * @param savedInstanceState If the fragment is being re-created from 1152 * a previous saved state, this is the state. 1153 */ 1154 public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) { 1155 onInflate(attrs, savedInstanceState); 1156 mCalled = true; 1157 } 1158 1159 /** 1160 * Called when a fragment is first attached to its activity. 1161 * {@link #onCreate(Bundle)} will be called after this. 1162 */ 1163 public void onAttach(Activity activity) { 1164 mCalled = true; 1165 } 1166 1167 /** 1168 * Called when a fragment loads an animation. 1169 */ 1170 public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) { 1171 return null; 1172 } 1173 1174 /** 1175 * Called to do initial creation of a fragment. This is called after 1176 * {@link #onAttach(Activity)} and before 1177 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}. 1178 * 1179 * <p>Note that this can be called while the fragment's activity is 1180 * still in the process of being created. As such, you can not rely 1181 * on things like the activity's content view hierarchy being initialized 1182 * at this point. If you want to do work once the activity itself is 1183 * created, see {@link #onActivityCreated(Bundle)}. 1184 * 1185 * @param savedInstanceState If the fragment is being re-created from 1186 * a previous saved state, this is the state. 1187 */ 1188 public void onCreate(Bundle savedInstanceState) { 1189 mCalled = true; 1190 } 1191 1192 /** 1193 * Called to have the fragment instantiate its user interface view. 1194 * This is optional, and non-graphical fragments can return null (which 1195 * is the default implementation). This will be called between 1196 * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}. 1197 * 1198 * <p>If you return a View from here, you will later be called in 1199 * {@link #onDestroyView} when the view is being released. 1200 * 1201 * @param inflater The LayoutInflater object that can be used to inflate 1202 * any views in the fragment, 1203 * @param container If non-null, this is the parent view that the fragment's 1204 * UI should be attached to. The fragment should not add the view itself, 1205 * but this can be used to generate the LayoutParams of the view. 1206 * @param savedInstanceState If non-null, this fragment is being re-constructed 1207 * from a previous saved state as given here. 1208 * 1209 * @return Return the View for the fragment's UI, or null. 1210 */ 1211 public View onCreateView(LayoutInflater inflater, ViewGroup container, 1212 Bundle savedInstanceState) { 1213 return null; 1214 } 1215 1216 /** 1217 * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} 1218 * has returned, but before any saved state has been restored in to the view. 1219 * This gives subclasses a chance to initialize themselves once 1220 * they know their view hierarchy has been completely created. The fragment's 1221 * view hierarchy is not however attached to its parent at this point. 1222 * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}. 1223 * @param savedInstanceState If non-null, this fragment is being re-constructed 1224 * from a previous saved state as given here. 1225 */ 1226 public void onViewCreated(View view, Bundle savedInstanceState) { 1227 } 1228 1229 /** 1230 * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}), 1231 * if provided. 1232 * 1233 * @return The fragment's root view, or null if it has no layout. 1234 */ 1235 public View getView() { 1236 return mView; 1237 } 1238 1239 /** 1240 * Called when the fragment's activity has been created and this 1241 * fragment's view hierarchy instantiated. It can be used to do final 1242 * initialization once these pieces are in place, such as retrieving 1243 * views or restoring state. It is also useful for fragments that use 1244 * {@link #setRetainInstance(boolean)} to retain their instance, 1245 * as this callback tells the fragment when it is fully associated with 1246 * the new activity instance. This is called after {@link #onCreateView} 1247 * and before {@link #onViewStateRestored(Bundle)}. 1248 * 1249 * @param savedInstanceState If the fragment is being re-created from 1250 * a previous saved state, this is the state. 1251 */ 1252 public void onActivityCreated(Bundle savedInstanceState) { 1253 mCalled = true; 1254 } 1255 1256 /** 1257 * Called when all saved state has been restored into the view hierarchy 1258 * of the fragment. This can be used to do initialization based on saved 1259 * state that you are letting the view hierarchy track itself, such as 1260 * whether check box widgets are currently checked. This is called 1261 * after {@link #onActivityCreated(Bundle)} and before 1262 * {@link #onStart()}. 1263 * 1264 * @param savedInstanceState If the fragment is being re-created from 1265 * a previous saved state, this is the state. 1266 */ 1267 public void onViewStateRestored(Bundle savedInstanceState) { 1268 mCalled = true; 1269 } 1270 1271 /** 1272 * Called when the Fragment is visible to the user. This is generally 1273 * tied to {@link Activity#onStart() Activity.onStart} of the containing 1274 * Activity's lifecycle. 1275 */ 1276 public void onStart() { 1277 mCalled = true; 1278 1279 if (!mLoadersStarted) { 1280 mLoadersStarted = true; 1281 if (!mCheckedForLoaderManager) { 1282 mCheckedForLoaderManager = true; 1283 mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false); 1284 } 1285 if (mLoaderManager != null) { 1286 mLoaderManager.doStart(); 1287 } 1288 } 1289 } 1290 1291 /** 1292 * Called when the fragment is visible to the user and actively running. 1293 * This is generally 1294 * tied to {@link Activity#onResume() Activity.onResume} of the containing 1295 * Activity's lifecycle. 1296 */ 1297 public void onResume() { 1298 mCalled = true; 1299 } 1300 1301 /** 1302 * Called to ask the fragment to save its current dynamic state, so it 1303 * can later be reconstructed in a new instance of its process is 1304 * restarted. If a new instance of the fragment later needs to be 1305 * created, the data you place in the Bundle here will be available 1306 * in the Bundle given to {@link #onCreate(Bundle)}, 1307 * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}, and 1308 * {@link #onActivityCreated(Bundle)}. 1309 * 1310 * <p>This corresponds to {@link Activity#onSaveInstanceState(Bundle) 1311 * Activity.onSaveInstanceState(Bundle)} and most of the discussion there 1312 * applies here as well. Note however: <em>this method may be called 1313 * at any time before {@link #onDestroy()}</em>. There are many situations 1314 * where a fragment may be mostly torn down (such as when placed on the 1315 * back stack with no UI showing), but its state will not be saved until 1316 * its owning activity actually needs to save its state. 1317 * 1318 * @param outState Bundle in which to place your saved state. 1319 */ 1320 public void onSaveInstanceState(Bundle outState) { 1321 } 1322 1323 public void onConfigurationChanged(Configuration newConfig) { 1324 mCalled = true; 1325 } 1326 1327 /** 1328 * Called when the Fragment is no longer resumed. This is generally 1329 * tied to {@link Activity#onPause() Activity.onPause} of the containing 1330 * Activity's lifecycle. 1331 */ 1332 public void onPause() { 1333 mCalled = true; 1334 } 1335 1336 /** 1337 * Called when the Fragment is no longer started. This is generally 1338 * tied to {@link Activity#onStop() Activity.onStop} of the containing 1339 * Activity's lifecycle. 1340 */ 1341 public void onStop() { 1342 mCalled = true; 1343 } 1344 1345 public void onLowMemory() { 1346 mCalled = true; 1347 } 1348 1349 public void onTrimMemory(int level) { 1350 mCalled = true; 1351 } 1352 1353 /** 1354 * Called when the view previously created by {@link #onCreateView} has 1355 * been detached from the fragment. The next time the fragment needs 1356 * to be displayed, a new view will be created. This is called 1357 * after {@link #onStop()} and before {@link #onDestroy()}. It is called 1358 * <em>regardless</em> of whether {@link #onCreateView} returned a 1359 * non-null view. Internally it is called after the view's state has 1360 * been saved but before it has been removed from its parent. 1361 */ 1362 public void onDestroyView() { 1363 mCalled = true; 1364 } 1365 1366 /** 1367 * Called when the fragment is no longer in use. This is called 1368 * after {@link #onStop()} and before {@link #onDetach()}. 1369 */ 1370 public void onDestroy() { 1371 mCalled = true; 1372 //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager 1373 // + " mLoaderManager=" + mLoaderManager); 1374 if (!mCheckedForLoaderManager) { 1375 mCheckedForLoaderManager = true; 1376 mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false); 1377 } 1378 if (mLoaderManager != null) { 1379 mLoaderManager.doDestroy(); 1380 } 1381 } 1382 1383 /** 1384 * Called by the fragment manager once this fragment has been removed, 1385 * so that we don't have any left-over state if the application decides 1386 * to re-use the instance. This only clears state that the framework 1387 * internally manages, not things the application sets. 1388 */ 1389 void initState() { 1390 mIndex = -1; 1391 mWho = null; 1392 mAdded = false; 1393 mRemoving = false; 1394 mResumed = false; 1395 mFromLayout = false; 1396 mInLayout = false; 1397 mRestored = false; 1398 mBackStackNesting = 0; 1399 mFragmentManager = null; 1400 mActivity = null; 1401 mFragmentId = 0; 1402 mContainerId = 0; 1403 mTag = null; 1404 mHidden = false; 1405 mDetached = false; 1406 mRetaining = false; 1407 mLoaderManager = null; 1408 mLoadersStarted = false; 1409 mCheckedForLoaderManager = false; 1410 } 1411 1412 /** 1413 * Called when the fragment is no longer attached to its activity. This 1414 * is called after {@link #onDestroy()}. 1415 */ 1416 public void onDetach() { 1417 mCalled = true; 1418 } 1419 1420 /** 1421 * Initialize the contents of the Activity's standard options menu. You 1422 * should place your menu items in to <var>menu</var>. For this method 1423 * to be called, you must have first called {@link #setHasOptionsMenu}. See 1424 * {@link Activity#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu} 1425 * for more information. 1426 * 1427 * @param menu The options menu in which you place your items. 1428 * 1429 * @see #setHasOptionsMenu 1430 * @see #onPrepareOptionsMenu 1431 * @see #onOptionsItemSelected 1432 */ 1433 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 1434 } 1435 1436 /** 1437 * Prepare the Screen's standard options menu to be displayed. This is 1438 * called right before the menu is shown, every time it is shown. You can 1439 * use this method to efficiently enable/disable items or otherwise 1440 * dynamically modify the contents. See 1441 * {@link Activity#onPrepareOptionsMenu(Menu) Activity.onPrepareOptionsMenu} 1442 * for more information. 1443 * 1444 * @param menu The options menu as last shown or first initialized by 1445 * onCreateOptionsMenu(). 1446 * 1447 * @see #setHasOptionsMenu 1448 * @see #onCreateOptionsMenu 1449 */ 1450 public void onPrepareOptionsMenu(Menu menu) { 1451 } 1452 1453 /** 1454 * Called when this fragment's option menu items are no longer being 1455 * included in the overall options menu. Receiving this call means that 1456 * the menu needed to be rebuilt, but this fragment's items were not 1457 * included in the newly built menu (its {@link #onCreateOptionsMenu(Menu, MenuInflater)} 1458 * was not called). 1459 */ 1460 public void onDestroyOptionsMenu() { 1461 } 1462 1463 /** 1464 * This hook is called whenever an item in your options menu is selected. 1465 * The default implementation simply returns false to have the normal 1466 * processing happen (calling the item's Runnable or sending a message to 1467 * its Handler as appropriate). You can use this method for any items 1468 * for which you would like to do processing without those other 1469 * facilities. 1470 * 1471 * <p>Derived classes should call through to the base class for it to 1472 * perform the default menu handling. 1473 * 1474 * @param item The menu item that was selected. 1475 * 1476 * @return boolean Return false to allow normal menu processing to 1477 * proceed, true to consume it here. 1478 * 1479 * @see #onCreateOptionsMenu 1480 */ 1481 public boolean onOptionsItemSelected(MenuItem item) { 1482 return false; 1483 } 1484 1485 /** 1486 * This hook is called whenever the options menu is being closed (either by the user canceling 1487 * the menu with the back/menu button, or when an item is selected). 1488 * 1489 * @param menu The options menu as last shown or first initialized by 1490 * onCreateOptionsMenu(). 1491 */ 1492 public void onOptionsMenuClosed(Menu menu) { 1493 } 1494 1495 /** 1496 * Called when a context menu for the {@code view} is about to be shown. 1497 * Unlike {@link #onCreateOptionsMenu}, this will be called every 1498 * time the context menu is about to be shown and should be populated for 1499 * the view (or item inside the view for {@link AdapterView} subclasses, 1500 * this can be found in the {@code menuInfo})). 1501 * <p> 1502 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an 1503 * item has been selected. 1504 * <p> 1505 * The default implementation calls up to 1506 * {@link Activity#onCreateContextMenu Activity.onCreateContextMenu}, though 1507 * you can not call this implementation if you don't want that behavior. 1508 * <p> 1509 * It is not safe to hold onto the context menu after this method returns. 1510 * {@inheritDoc} 1511 */ 1512 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 1513 getActivity().onCreateContextMenu(menu, v, menuInfo); 1514 } 1515 1516 /** 1517 * Registers a context menu to be shown for the given view (multiple views 1518 * can show the context menu). This method will set the 1519 * {@link OnCreateContextMenuListener} on the view to this fragment, so 1520 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be 1521 * called when it is time to show the context menu. 1522 * 1523 * @see #unregisterForContextMenu(View) 1524 * @param view The view that should show a context menu. 1525 */ 1526 public void registerForContextMenu(View view) { 1527 view.setOnCreateContextMenuListener(this); 1528 } 1529 1530 /** 1531 * Prevents a context menu to be shown for the given view. This method will 1532 * remove the {@link OnCreateContextMenuListener} on the view. 1533 * 1534 * @see #registerForContextMenu(View) 1535 * @param view The view that should stop showing a context menu. 1536 */ 1537 public void unregisterForContextMenu(View view) { 1538 view.setOnCreateContextMenuListener(null); 1539 } 1540 1541 /** 1542 * This hook is called whenever an item in a context menu is selected. The 1543 * default implementation simply returns false to have the normal processing 1544 * happen (calling the item's Runnable or sending a message to its Handler 1545 * as appropriate). You can use this method for any items for which you 1546 * would like to do processing without those other facilities. 1547 * <p> 1548 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the 1549 * View that added this menu item. 1550 * <p> 1551 * Derived classes should call through to the base class for it to perform 1552 * the default menu handling. 1553 * 1554 * @param item The context menu item that was selected. 1555 * @return boolean Return false to allow normal context menu processing to 1556 * proceed, true to consume it here. 1557 */ 1558 public boolean onContextItemSelected(MenuItem item) { 1559 return false; 1560 } 1561 1562 /** 1563 * Print the Fragments's state into the given stream. 1564 * 1565 * @param prefix Text to print at the front of each line. 1566 * @param fd The raw file descriptor that the dump is being sent to. 1567 * @param writer The PrintWriter to which you should dump your state. This will be 1568 * closed for you after you return. 1569 * @param args additional arguments to the dump request. 1570 */ 1571 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 1572 writer.print(prefix); writer.print("mFragmentId=#"); 1573 writer.print(Integer.toHexString(mFragmentId)); 1574 writer.print(" mContainerId=#"); 1575 writer.print(Integer.toHexString(mContainerId)); 1576 writer.print(" mTag="); writer.println(mTag); 1577 writer.print(prefix); writer.print("mState="); writer.print(mState); 1578 writer.print(" mIndex="); writer.print(mIndex); 1579 writer.print(" mWho="); writer.print(mWho); 1580 writer.print(" mBackStackNesting="); writer.println(mBackStackNesting); 1581 writer.print(prefix); writer.print("mAdded="); writer.print(mAdded); 1582 writer.print(" mRemoving="); writer.print(mRemoving); 1583 writer.print(" mResumed="); writer.print(mResumed); 1584 writer.print(" mFromLayout="); writer.print(mFromLayout); 1585 writer.print(" mInLayout="); writer.println(mInLayout); 1586 writer.print(prefix); writer.print("mHidden="); writer.print(mHidden); 1587 writer.print(" mDetached="); writer.print(mDetached); 1588 writer.print(" mMenuVisible="); writer.print(mMenuVisible); 1589 writer.print(" mHasMenu="); writer.println(mHasMenu); 1590 writer.print(prefix); writer.print("mRetainInstance="); writer.print(mRetainInstance); 1591 writer.print(" mRetaining="); writer.print(mRetaining); 1592 writer.print(" mUserVisibleHint="); writer.println(mUserVisibleHint); 1593 if (mFragmentManager != null) { 1594 writer.print(prefix); writer.print("mFragmentManager="); 1595 writer.println(mFragmentManager); 1596 } 1597 if (mActivity != null) { 1598 writer.print(prefix); writer.print("mActivity="); 1599 writer.println(mActivity); 1600 } 1601 if (mParentFragment != null) { 1602 writer.print(prefix); writer.print("mParentFragment="); 1603 writer.println(mParentFragment); 1604 } 1605 if (mArguments != null) { 1606 writer.print(prefix); writer.print("mArguments="); writer.println(mArguments); 1607 } 1608 if (mSavedFragmentState != null) { 1609 writer.print(prefix); writer.print("mSavedFragmentState="); 1610 writer.println(mSavedFragmentState); 1611 } 1612 if (mSavedViewState != null) { 1613 writer.print(prefix); writer.print("mSavedViewState="); 1614 writer.println(mSavedViewState); 1615 } 1616 if (mTarget != null) { 1617 writer.print(prefix); writer.print("mTarget="); writer.print(mTarget); 1618 writer.print(" mTargetRequestCode="); 1619 writer.println(mTargetRequestCode); 1620 } 1621 if (mNextAnim != 0) { 1622 writer.print(prefix); writer.print("mNextAnim="); writer.println(mNextAnim); 1623 } 1624 if (mContainer != null) { 1625 writer.print(prefix); writer.print("mContainer="); writer.println(mContainer); 1626 } 1627 if (mView != null) { 1628 writer.print(prefix); writer.print("mView="); writer.println(mView); 1629 } 1630 if (mAnimatingAway != null) { 1631 writer.print(prefix); writer.print("mAnimatingAway="); writer.println(mAnimatingAway); 1632 writer.print(prefix); writer.print("mStateAfterAnimating="); 1633 writer.println(mStateAfterAnimating); 1634 } 1635 if (mLoaderManager != null) { 1636 writer.print(prefix); writer.println("Loader Manager:"); 1637 mLoaderManager.dump(prefix + " ", fd, writer, args); 1638 } 1639 if (mChildFragmentManager != null) { 1640 writer.print(prefix); writer.println("Child " + mChildFragmentManager + ":"); 1641 mChildFragmentManager.dump(prefix + " ", fd, writer, args); 1642 } 1643 } 1644 1645 Fragment findFragmentByWho(String who) { 1646 if (who.equals(mWho)) { 1647 return this; 1648 } 1649 if (mChildFragmentManager != null) { 1650 return mChildFragmentManager.findFragmentByWho(who); 1651 } 1652 return null; 1653 } 1654 1655 void instantiateChildFragmentManager() { 1656 mChildFragmentManager = new FragmentManagerImpl(); 1657 mChildFragmentManager.attachActivity(mActivity, new FragmentContainer() { 1658 @Override 1659 public View findViewById(int id) { 1660 if (mView == null) { 1661 throw new IllegalStateException("Fragment does not have a view"); 1662 } 1663 return mView.findViewById(id); 1664 } 1665 }, this); 1666 } 1667 1668 void performCreate(Bundle savedInstanceState) { 1669 if (mChildFragmentManager != null) { 1670 mChildFragmentManager.noteStateNotSaved(); 1671 } 1672 mCalled = false; 1673 onCreate(savedInstanceState); 1674 if (!mCalled) { 1675 throw new SuperNotCalledException("Fragment " + this 1676 + " did not call through to super.onCreate()"); 1677 } 1678 if (savedInstanceState != null) { 1679 Parcelable p = savedInstanceState.getParcelable(Activity.FRAGMENTS_TAG); 1680 if (p != null) { 1681 if (mChildFragmentManager == null) { 1682 instantiateChildFragmentManager(); 1683 } 1684 mChildFragmentManager.restoreAllState(p, null); 1685 mChildFragmentManager.dispatchCreate(); 1686 } 1687 } 1688 } 1689 1690 View performCreateView(LayoutInflater inflater, ViewGroup container, 1691 Bundle savedInstanceState) { 1692 if (mChildFragmentManager != null) { 1693 mChildFragmentManager.noteStateNotSaved(); 1694 } 1695 return onCreateView(inflater, container, savedInstanceState); 1696 } 1697 1698 void performActivityCreated(Bundle savedInstanceState) { 1699 if (mChildFragmentManager != null) { 1700 mChildFragmentManager.noteStateNotSaved(); 1701 } 1702 mCalled = false; 1703 onActivityCreated(savedInstanceState); 1704 if (!mCalled) { 1705 throw new SuperNotCalledException("Fragment " + this 1706 + " did not call through to super.onActivityCreated()"); 1707 } 1708 if (mChildFragmentManager != null) { 1709 mChildFragmentManager.dispatchActivityCreated(); 1710 } 1711 } 1712 1713 void performStart() { 1714 if (mChildFragmentManager != null) { 1715 mChildFragmentManager.noteStateNotSaved(); 1716 mChildFragmentManager.execPendingActions(); 1717 } 1718 mCalled = false; 1719 onStart(); 1720 if (!mCalled) { 1721 throw new SuperNotCalledException("Fragment " + this 1722 + " did not call through to super.onStart()"); 1723 } 1724 if (mChildFragmentManager != null) { 1725 mChildFragmentManager.dispatchStart(); 1726 } 1727 if (mLoaderManager != null) { 1728 mLoaderManager.doReportStart(); 1729 } 1730 } 1731 1732 void performResume() { 1733 if (mChildFragmentManager != null) { 1734 mChildFragmentManager.noteStateNotSaved(); 1735 mChildFragmentManager.execPendingActions(); 1736 } 1737 mCalled = false; 1738 onResume(); 1739 if (!mCalled) { 1740 throw new SuperNotCalledException("Fragment " + this 1741 + " did not call through to super.onResume()"); 1742 } 1743 if (mChildFragmentManager != null) { 1744 mChildFragmentManager.dispatchResume(); 1745 mChildFragmentManager.execPendingActions(); 1746 } 1747 } 1748 1749 void performConfigurationChanged(Configuration newConfig) { 1750 onConfigurationChanged(newConfig); 1751 if (mChildFragmentManager != null) { 1752 mChildFragmentManager.dispatchConfigurationChanged(newConfig); 1753 } 1754 } 1755 1756 void performLowMemory() { 1757 onLowMemory(); 1758 if (mChildFragmentManager != null) { 1759 mChildFragmentManager.dispatchLowMemory(); 1760 } 1761 } 1762 1763 void performTrimMemory(int level) { 1764 onTrimMemory(level); 1765 if (mChildFragmentManager != null) { 1766 mChildFragmentManager.dispatchTrimMemory(level); 1767 } 1768 } 1769 1770 boolean performCreateOptionsMenu(Menu menu, MenuInflater inflater) { 1771 boolean show = false; 1772 if (!mHidden) { 1773 if (mHasMenu && mMenuVisible) { 1774 show = true; 1775 onCreateOptionsMenu(menu, inflater); 1776 } 1777 if (mChildFragmentManager != null) { 1778 show |= mChildFragmentManager.dispatchCreateOptionsMenu(menu, inflater); 1779 } 1780 } 1781 return show; 1782 } 1783 1784 boolean performPrepareOptionsMenu(Menu menu) { 1785 boolean show = false; 1786 if (!mHidden) { 1787 if (mHasMenu && mMenuVisible) { 1788 show = true; 1789 onPrepareOptionsMenu(menu); 1790 } 1791 if (mChildFragmentManager != null) { 1792 show |= mChildFragmentManager.dispatchPrepareOptionsMenu(menu); 1793 } 1794 } 1795 return show; 1796 } 1797 1798 boolean performOptionsItemSelected(MenuItem item) { 1799 if (!mHidden) { 1800 if (mHasMenu && mMenuVisible) { 1801 if (onOptionsItemSelected(item)) { 1802 return true; 1803 } 1804 } 1805 if (mChildFragmentManager != null) { 1806 if (mChildFragmentManager.dispatchOptionsItemSelected(item)) { 1807 return true; 1808 } 1809 } 1810 } 1811 return false; 1812 } 1813 1814 boolean performContextItemSelected(MenuItem item) { 1815 if (!mHidden) { 1816 if (onContextItemSelected(item)) { 1817 return true; 1818 } 1819 if (mChildFragmentManager != null) { 1820 if (mChildFragmentManager.dispatchContextItemSelected(item)) { 1821 return true; 1822 } 1823 } 1824 } 1825 return false; 1826 } 1827 1828 void performOptionsMenuClosed(Menu menu) { 1829 if (!mHidden) { 1830 if (mHasMenu && mMenuVisible) { 1831 onOptionsMenuClosed(menu); 1832 } 1833 if (mChildFragmentManager != null) { 1834 mChildFragmentManager.dispatchOptionsMenuClosed(menu); 1835 } 1836 } 1837 } 1838 1839 void performSaveInstanceState(Bundle outState) { 1840 onSaveInstanceState(outState); 1841 if (mChildFragmentManager != null) { 1842 Parcelable p = mChildFragmentManager.saveAllState(); 1843 if (p != null) { 1844 outState.putParcelable(Activity.FRAGMENTS_TAG, p); 1845 } 1846 } 1847 } 1848 1849 void performPause() { 1850 if (mChildFragmentManager != null) { 1851 mChildFragmentManager.dispatchPause(); 1852 } 1853 mCalled = false; 1854 onPause(); 1855 if (!mCalled) { 1856 throw new SuperNotCalledException("Fragment " + this 1857 + " did not call through to super.onPause()"); 1858 } 1859 } 1860 1861 void performStop() { 1862 if (mChildFragmentManager != null) { 1863 mChildFragmentManager.dispatchStop(); 1864 } 1865 mCalled = false; 1866 onStop(); 1867 if (!mCalled) { 1868 throw new SuperNotCalledException("Fragment " + this 1869 + " did not call through to super.onStop()"); 1870 } 1871 1872 if (mLoadersStarted) { 1873 mLoadersStarted = false; 1874 if (!mCheckedForLoaderManager) { 1875 mCheckedForLoaderManager = true; 1876 mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false); 1877 } 1878 if (mLoaderManager != null) { 1879 if (mActivity == null || !mActivity.mChangingConfigurations) { 1880 mLoaderManager.doStop(); 1881 } else { 1882 mLoaderManager.doRetain(); 1883 } 1884 } 1885 } 1886 } 1887 1888 void performDestroyView() { 1889 if (mChildFragmentManager != null) { 1890 mChildFragmentManager.dispatchDestroyView(); 1891 } 1892 mCalled = false; 1893 onDestroyView(); 1894 if (!mCalled) { 1895 throw new SuperNotCalledException("Fragment " + this 1896 + " did not call through to super.onDestroyView()"); 1897 } 1898 if (mLoaderManager != null) { 1899 mLoaderManager.doReportNextStart(); 1900 } 1901 } 1902 1903 void performDestroy() { 1904 if (mChildFragmentManager != null) { 1905 mChildFragmentManager.dispatchDestroy(); 1906 } 1907 mCalled = false; 1908 onDestroy(); 1909 if (!mCalled) { 1910 throw new SuperNotCalledException("Fragment " + this 1911 + " did not call through to super.onDestroy()"); 1912 } 1913 } 1914 } 1915