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