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