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