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