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