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