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