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