FragmentActivity.java revision 59a123238b4d4e54cdca583b30b5776168461862
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.Context; 21import android.content.Intent; 22import android.content.res.Configuration; 23import android.content.res.Resources; 24import android.os.Bundle; 25import android.os.Handler; 26import android.os.Message; 27import android.os.Parcelable; 28import android.support.annotation.NonNull; 29import android.support.annotation.Nullable; 30import android.support.v4.util.SimpleArrayMap; 31import android.util.AttributeSet; 32import android.util.Log; 33import android.view.KeyEvent; 34import android.view.LayoutInflater; 35import android.view.Menu; 36import android.view.MenuItem; 37import android.view.View; 38import android.view.ViewGroup; 39import android.view.Window; 40 41import java.io.FileDescriptor; 42import java.io.PrintWriter; 43import java.util.ArrayList; 44import java.util.List; 45 46/** 47 * Base class for activities that want to use the support-based 48 * {@link android.support.v4.app.Fragment} and 49 * {@link android.support.v4.content.Loader} APIs. 50 * 51 * <p>When using this class as opposed to new platform's built-in fragment 52 * and loader support, you must use the {@link #getSupportFragmentManager()} 53 * and {@link #getSupportLoaderManager()} methods respectively to access 54 * those features. 55 * 56 * <p class="note"><strong>Note:</strong> If you want to implement an activity that includes 57 * an <a href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>, you should instead use 58 * the {@link android.support.v7.app.ActionBarActivity} class, which is a subclass of this one, 59 * so allows you to use {@link android.support.v4.app.Fragment} APIs on API level 7 and higher.</p> 60 * 61 * <p>Known limitations:</p> 62 * <ul> 63 * <li> <p>When using the <code><fragment></code> tag, this implementation can not 64 * use the parent view's ID as the new fragment's ID. You must explicitly 65 * specify an ID (or tag) in the <code><fragment></code>.</p> 66 * <li> <p>Prior to Honeycomb (3.0), an activity's state was saved before pausing. 67 * Fragments are a significant amount of new state, and dynamic enough that one 68 * often wants them to change between pausing and stopping. These classes 69 * throw an exception if you try to change the fragment state after it has been 70 * saved, to avoid accidental loss of UI state. However this is too restrictive 71 * prior to Honeycomb, where the state is saved before pausing. To address this, 72 * when running on platforms prior to Honeycomb an exception will not be thrown 73 * if you change fragments between the state save and the activity being stopped. 74 * This means that in some cases if the activity is restored from its last saved 75 * state, this may be a snapshot slightly before what the user last saw.</p> 76 * </ul> 77 */ 78public class FragmentActivity extends BaseFragmentActivityHoneycomb { 79 private static final String TAG = "FragmentActivity"; 80 81 static final String FRAGMENTS_TAG = "android:support:fragments"; 82 83 // This is the SDK API version of Honeycomb (3.0). 84 private static final int HONEYCOMB = 11; 85 86 static final int MSG_REALLY_STOPPED = 1; 87 static final int MSG_RESUME_PENDING = 2; 88 89 final Handler mHandler = new Handler() { 90 @Override 91 public void handleMessage(Message msg) { 92 switch (msg.what) { 93 case MSG_REALLY_STOPPED: 94 if (mStopped) { 95 doReallyStop(false); 96 } 97 break; 98 case MSG_RESUME_PENDING: 99 onResumeFragments(); 100 mFragments.execPendingActions(); 101 break; 102 default: 103 super.handleMessage(msg); 104 } 105 } 106 107 }; 108 final FragmentController mFragments = FragmentController.createController(new HostCallbacks()); 109 110 boolean mCreated; 111 boolean mResumed; 112 boolean mStopped; 113 boolean mReallyStopped; 114 boolean mRetaining; 115 116 boolean mOptionsMenuInvalidated; 117 118 static final class NonConfigurationInstances { 119 Object custom; 120 List<Fragment> fragments; 121 SimpleArrayMap<String, LoaderManager> loaders; 122 } 123 124 // ------------------------------------------------------------------------ 125 // HOOKS INTO ACTIVITY 126 // ------------------------------------------------------------------------ 127 128 /** 129 * Dispatch incoming result to the correct fragment. 130 */ 131 @Override 132 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 133 mFragments.noteStateNotSaved(); 134 int index = requestCode>>16; 135 if (index != 0) { 136 index--; 137 final int activeFragmentsCount = mFragments.getActiveFragmentsCount(); 138 if (activeFragmentsCount == 0 || index < 0 || index >= activeFragmentsCount) { 139 Log.w(TAG, "Activity result fragment index out of range: 0x" 140 + Integer.toHexString(requestCode)); 141 return; 142 } 143 final List<Fragment> activeFragments = 144 mFragments.getActiveFragments(new ArrayList<Fragment>(activeFragmentsCount)); 145 Fragment frag = activeFragments.get(index); 146 if (frag == null) { 147 Log.w(TAG, "Activity result no fragment exists for index: 0x" 148 + Integer.toHexString(requestCode)); 149 } else { 150 frag.onActivityResult(requestCode&0xffff, resultCode, data); 151 } 152 return; 153 } 154 155 super.onActivityResult(requestCode, resultCode, data); 156 } 157 158 /** 159 * Take care of popping the fragment back stack or finishing the activity 160 * as appropriate. 161 */ 162 public void onBackPressed() { 163 if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) { 164 supportFinishAfterTransition(); 165 } 166 } 167 168 /** 169 * Reverses the Activity Scene entry Transition and triggers the calling Activity 170 * to reverse its exit Transition. When the exit Transition completes, 171 * {@link #finish()} is called. If no entry Transition was used, finish() is called 172 * immediately and the Activity exit Transition is run. 173 * 174 * <p>On Android 4.4 or lower, this method only finishes the Activity with no 175 * special exit transition.</p> 176 */ 177 public void supportFinishAfterTransition() { 178 ActivityCompat.finishAfterTransition(this); 179 } 180 181 /** 182 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, 183 * android.view.View, String)} was used to start an Activity, <var>callback</var> 184 * will be called to handle shared elements on the <i>launched</i> Activity. This requires 185 * {@link Window#FEATURE_CONTENT_TRANSITIONS}. 186 * 187 * @param callback Used to manipulate shared element transitions on the launched Activity. 188 */ 189 public void setEnterSharedElementCallback(SharedElementCallback callback) { 190 ActivityCompat.setEnterSharedElementCallback(this, callback); 191 } 192 193 /** 194 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, 195 * android.view.View, String)} was used to start an Activity, <var>listener</var> 196 * will be called to handle shared elements on the <i>launching</i> Activity. Most 197 * calls will only come when returning from the started Activity. 198 * This requires {@link Window#FEATURE_CONTENT_TRANSITIONS}. 199 * 200 * @param listener Used to manipulate shared element transitions on the launching Activity. 201 */ 202 public void setExitSharedElementCallback(SharedElementCallback listener) { 203 ActivityCompat.setExitSharedElementCallback(this, listener); 204 } 205 206 /** 207 * Support library version of {@link android.app.Activity#postponeEnterTransition()} that works 208 * only on API 21 and later. 209 */ 210 public void supportPostponeEnterTransition() { 211 ActivityCompat.postponeEnterTransition(this); 212 } 213 214 /** 215 * Support library version of {@link android.app.Activity#startPostponedEnterTransition()} 216 * that only works with API 21 and later. 217 */ 218 public void supportStartPostponedEnterTransition() { 219 ActivityCompat.startPostponedEnterTransition(this); 220 } 221 222 /** 223 * Dispatch configuration change to all fragments. 224 */ 225 @Override 226 public void onConfigurationChanged(Configuration newConfig) { 227 super.onConfigurationChanged(newConfig); 228 mFragments.dispatchConfigurationChanged(newConfig); 229 } 230 231 /** 232 * Perform initialization of all fragments and loaders. 233 */ 234 @SuppressWarnings("deprecation") 235 @Override 236 protected void onCreate(@Nullable Bundle savedInstanceState) { 237 mFragments.attachHost(null /*parent*/); 238 239 super.onCreate(savedInstanceState); 240 241 NonConfigurationInstances nc = 242 (NonConfigurationInstances) getLastNonConfigurationInstance(); 243 if (nc != null) { 244 mFragments.restoreLoaderNonConfig(nc.loaders); 245 } 246 if (savedInstanceState != null) { 247 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG); 248 mFragments.restoreAllState(p, nc != null ? nc.fragments : null); 249 } 250 mFragments.dispatchCreate(); 251 } 252 253 /** 254 * Dispatch to Fragment.onCreateOptionsMenu(). 255 */ 256 @Override 257 public boolean onCreatePanelMenu(int featureId, Menu menu) { 258 if (featureId == Window.FEATURE_OPTIONS_PANEL) { 259 boolean show = super.onCreatePanelMenu(featureId, menu); 260 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater()); 261 if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) { 262 return show; 263 } 264 // Prior to Honeycomb, the framework can't invalidate the options 265 // menu, so we must always say we have one in case the app later 266 // invalidates it and needs to have it shown. 267 return true; 268 } 269 return super.onCreatePanelMenu(featureId, menu); 270 } 271 272 @Override 273 final View dispatchFragmentsOnCreateView(View parent, String name, Context context, 274 AttributeSet attrs) { 275 return mFragments.onCreateView(parent, name, context, attrs); 276 } 277 278 /** 279 * Destroy all fragments and loaders. 280 */ 281 @Override 282 protected void onDestroy() { 283 super.onDestroy(); 284 285 doReallyStop(false); 286 287 mFragments.dispatchDestroy(); 288 mFragments.doLoaderDestroy(); 289 } 290 291 /** 292 * Take care of calling onBackPressed() for pre-Eclair platforms. 293 */ 294 @Override 295 public boolean onKeyDown(int keyCode, KeyEvent event) { 296 if (android.os.Build.VERSION.SDK_INT < 5 /* ECLAIR */ 297 && keyCode == KeyEvent.KEYCODE_BACK 298 && event.getRepeatCount() == 0) { 299 // Take care of calling this method on earlier versions of 300 // the platform where it doesn't exist. 301 onBackPressed(); 302 return true; 303 } 304 305 return super.onKeyDown(keyCode, event); 306 } 307 308 /** 309 * Dispatch onLowMemory() to all fragments. 310 */ 311 @Override 312 public void onLowMemory() { 313 super.onLowMemory(); 314 mFragments.dispatchLowMemory(); 315 } 316 317 /** 318 * Dispatch context and options menu to fragments. 319 */ 320 @Override 321 public boolean onMenuItemSelected(int featureId, MenuItem item) { 322 if (super.onMenuItemSelected(featureId, item)) { 323 return true; 324 } 325 326 switch (featureId) { 327 case Window.FEATURE_OPTIONS_PANEL: 328 return mFragments.dispatchOptionsItemSelected(item); 329 330 case Window.FEATURE_CONTEXT_MENU: 331 return mFragments.dispatchContextItemSelected(item); 332 333 default: 334 return false; 335 } 336 } 337 338 /** 339 * Call onOptionsMenuClosed() on fragments. 340 */ 341 @Override 342 public void onPanelClosed(int featureId, Menu menu) { 343 switch (featureId) { 344 case Window.FEATURE_OPTIONS_PANEL: 345 mFragments.dispatchOptionsMenuClosed(menu); 346 break; 347 } 348 super.onPanelClosed(featureId, menu); 349 } 350 351 /** 352 * Dispatch onPause() to fragments. 353 */ 354 @Override 355 protected void onPause() { 356 super.onPause(); 357 mResumed = false; 358 if (mHandler.hasMessages(MSG_RESUME_PENDING)) { 359 mHandler.removeMessages(MSG_RESUME_PENDING); 360 onResumeFragments(); 361 } 362 mFragments.dispatchPause(); 363 } 364 365 /** 366 * Handle onNewIntent() to inform the fragment manager that the 367 * state is not saved. If you are handling new intents and may be 368 * making changes to the fragment state, you want to be sure to call 369 * through to the super-class here first. Otherwise, if your state 370 * is saved but the activity is not stopped, you could get an 371 * onNewIntent() call which happens before onResume() and trying to 372 * perform fragment operations at that point will throw IllegalStateException 373 * because the fragment manager thinks the state is still saved. 374 */ 375 @Override 376 protected void onNewIntent(Intent intent) { 377 super.onNewIntent(intent); 378 mFragments.noteStateNotSaved(); 379 } 380 381 /** 382 * Dispatch onResume() to fragments. Note that for better inter-operation 383 * with older versions of the platform, at the point of this call the 384 * fragments attached to the activity are <em>not</em> resumed. This means 385 * that in some cases the previous state may still be saved, not allowing 386 * fragment transactions that modify the state. To correctly interact 387 * with fragments in their proper state, you should instead override 388 * {@link #onResumeFragments()}. 389 */ 390 @Override 391 protected void onResume() { 392 super.onResume(); 393 mHandler.sendEmptyMessage(MSG_RESUME_PENDING); 394 mResumed = true; 395 mFragments.execPendingActions(); 396 } 397 398 /** 399 * Dispatch onResume() to fragments. 400 */ 401 @Override 402 protected void onPostResume() { 403 super.onPostResume(); 404 mHandler.removeMessages(MSG_RESUME_PENDING); 405 onResumeFragments(); 406 mFragments.execPendingActions(); 407 } 408 409 /** 410 * This is the fragment-orientated version of {@link #onResume()} that you 411 * can override to perform operations in the Activity at the same point 412 * where its fragments are resumed. Be sure to always call through to 413 * the super-class. 414 */ 415 protected void onResumeFragments() { 416 mFragments.dispatchResume(); 417 } 418 419 /** 420 * Dispatch onPrepareOptionsMenu() to fragments. 421 */ 422 @Override 423 public boolean onPreparePanel(int featureId, View view, Menu menu) { 424 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) { 425 if (mOptionsMenuInvalidated) { 426 mOptionsMenuInvalidated = false; 427 menu.clear(); 428 onCreatePanelMenu(featureId, menu); 429 } 430 boolean goforit = onPrepareOptionsPanel(view, menu); 431 goforit |= mFragments.dispatchPrepareOptionsMenu(menu); 432 return goforit; 433 } 434 return super.onPreparePanel(featureId, view, menu); 435 } 436 437 /** 438 * @hide 439 */ 440 protected boolean onPrepareOptionsPanel(View view, Menu menu) { 441 return super.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, view, menu); 442 } 443 444 /** 445 * Retain all appropriate fragment and loader state. You can NOT 446 * override this yourself! Use {@link #onRetainCustomNonConfigurationInstance()} 447 * if you want to retain your own state. 448 */ 449 @Override 450 public final Object onRetainNonConfigurationInstance() { 451 if (mStopped) { 452 doReallyStop(true); 453 } 454 455 Object custom = onRetainCustomNonConfigurationInstance(); 456 457 List<Fragment> fragments = mFragments.retainNonConfig(); 458 SimpleArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig(); 459 460 if (fragments == null && loaders == null && custom == null) { 461 return null; 462 } 463 464 NonConfigurationInstances nci = new NonConfigurationInstances(); 465 nci.custom = custom; 466 nci.fragments = fragments; 467 nci.loaders = loaders; 468 return nci; 469 } 470 471 /** 472 * Save all appropriate fragment state. 473 */ 474 @Override 475 protected void onSaveInstanceState(Bundle outState) { 476 super.onSaveInstanceState(outState); 477 Parcelable p = mFragments.saveAllState(); 478 if (p != null) { 479 outState.putParcelable(FRAGMENTS_TAG, p); 480 } 481 } 482 483 /** 484 * Dispatch onStart() to all fragments. Ensure any created loaders are 485 * now started. 486 */ 487 @Override 488 protected void onStart() { 489 super.onStart(); 490 491 mStopped = false; 492 mReallyStopped = false; 493 mHandler.removeMessages(MSG_REALLY_STOPPED); 494 495 if (!mCreated) { 496 mCreated = true; 497 mFragments.dispatchActivityCreated(); 498 } 499 500 mFragments.noteStateNotSaved(); 501 mFragments.execPendingActions(); 502 503 mFragments.doLoaderStart(); 504 505 // NOTE: HC onStart goes here. 506 507 mFragments.dispatchStart(); 508 mFragments.reportLoaderStart(); 509 } 510 511 /** 512 * Dispatch onStop() to all fragments. Ensure all loaders are stopped. 513 */ 514 @Override 515 protected void onStop() { 516 super.onStop(); 517 518 mStopped = true; 519 mHandler.sendEmptyMessage(MSG_REALLY_STOPPED); 520 521 mFragments.dispatchStop(); 522 } 523 524 // ------------------------------------------------------------------------ 525 // NEW METHODS 526 // ------------------------------------------------------------------------ 527 528 /** 529 * Use this instead of {@link #onRetainNonConfigurationInstance()}. 530 * Retrieve later with {@link #getLastCustomNonConfigurationInstance()}. 531 */ 532 public Object onRetainCustomNonConfigurationInstance() { 533 return null; 534 } 535 536 /** 537 * Return the value previously returned from 538 * {@link #onRetainCustomNonConfigurationInstance()}. 539 */ 540 @SuppressWarnings("deprecation") 541 public Object getLastCustomNonConfigurationInstance() { 542 NonConfigurationInstances nc = (NonConfigurationInstances) 543 getLastNonConfigurationInstance(); 544 return nc != null ? nc.custom : null; 545 } 546 547 /** 548 * Support library version of {@link Activity#invalidateOptionsMenu}. 549 * 550 * <p>Invalidate the activity's options menu. This will cause relevant presentations 551 * of the menu to fully update via calls to onCreateOptionsMenu and 552 * onPrepareOptionsMenu the next time the menu is requested. 553 */ 554 public void supportInvalidateOptionsMenu() { 555 if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) { 556 // If we are running on HC or greater, we can use the framework 557 // API to invalidate the options menu. 558 ActivityCompatHoneycomb.invalidateOptionsMenu(this); 559 return; 560 } 561 562 // Whoops, older platform... we'll use a hack, to manually rebuild 563 // the options menu the next time it is prepared. 564 mOptionsMenuInvalidated = true; 565 } 566 567 /** 568 * Print the Activity's state into the given stream. This gets invoked if 569 * you run "adb shell dumpsys activity <activity_component_name>". 570 * 571 * @param prefix Desired prefix to prepend at each line of output. 572 * @param fd The raw file descriptor that the dump is being sent to. 573 * @param writer The PrintWriter to which you should dump your state. This will be 574 * closed for you after you return. 575 * @param args additional arguments to the dump request. 576 */ 577 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 578 if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) { 579 // XXX This can only work if we can call the super-class impl. :/ 580 //ActivityCompatHoneycomb.dump(this, prefix, fd, writer, args); 581 } 582 writer.print(prefix); writer.print("Local FragmentActivity "); 583 writer.print(Integer.toHexString(System.identityHashCode(this))); 584 writer.println(" State:"); 585 String innerPrefix = prefix + " "; 586 writer.print(innerPrefix); writer.print("mCreated="); 587 writer.print(mCreated); writer.print("mResumed="); 588 writer.print(mResumed); writer.print(" mStopped="); 589 writer.print(mStopped); writer.print(" mReallyStopped="); 590 writer.println(mReallyStopped); 591 mFragments.dumpLoaders(innerPrefix, fd, writer, args); 592 mFragments.getSupportFragmentManager().dump(prefix, fd, writer, args); 593 writer.print(prefix); writer.println("View Hierarchy:"); 594 dumpViewHierarchy(prefix + " ", writer, getWindow().getDecorView()); 595 } 596 597 private static String viewToString(View view) { 598 StringBuilder out = new StringBuilder(128); 599 out.append(view.getClass().getName()); 600 out.append('{'); 601 out.append(Integer.toHexString(System.identityHashCode(view))); 602 out.append(' '); 603 switch (view.getVisibility()) { 604 case View.VISIBLE: out.append('V'); break; 605 case View.INVISIBLE: out.append('I'); break; 606 case View.GONE: out.append('G'); break; 607 default: out.append('.'); break; 608 } 609 out.append(view.isFocusable() ? 'F' : '.'); 610 out.append(view.isEnabled() ? 'E' : '.'); 611 out.append(view.willNotDraw() ? '.' : 'D'); 612 out.append(view.isHorizontalScrollBarEnabled()? 'H' : '.'); 613 out.append(view.isVerticalScrollBarEnabled() ? 'V' : '.'); 614 out.append(view.isClickable() ? 'C' : '.'); 615 out.append(view.isLongClickable() ? 'L' : '.'); 616 out.append(' '); 617 out.append(view.isFocused() ? 'F' : '.'); 618 out.append(view.isSelected() ? 'S' : '.'); 619 out.append(view.isPressed() ? 'P' : '.'); 620 out.append(' '); 621 out.append(view.getLeft()); 622 out.append(','); 623 out.append(view.getTop()); 624 out.append('-'); 625 out.append(view.getRight()); 626 out.append(','); 627 out.append(view.getBottom()); 628 final int id = view.getId(); 629 if (id != View.NO_ID) { 630 out.append(" #"); 631 out.append(Integer.toHexString(id)); 632 final Resources r = view.getResources(); 633 if (id != 0 && r != null) { 634 try { 635 String pkgname; 636 switch (id&0xff000000) { 637 case 0x7f000000: 638 pkgname="app"; 639 break; 640 case 0x01000000: 641 pkgname="android"; 642 break; 643 default: 644 pkgname = r.getResourcePackageName(id); 645 break; 646 } 647 String typename = r.getResourceTypeName(id); 648 String entryname = r.getResourceEntryName(id); 649 out.append(" "); 650 out.append(pkgname); 651 out.append(":"); 652 out.append(typename); 653 out.append("/"); 654 out.append(entryname); 655 } catch (Resources.NotFoundException e) { 656 } 657 } 658 } 659 out.append("}"); 660 return out.toString(); 661 } 662 663 private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) { 664 writer.print(prefix); 665 if (view == null) { 666 writer.println("null"); 667 return; 668 } 669 writer.println(viewToString(view)); 670 if (!(view instanceof ViewGroup)) { 671 return; 672 } 673 ViewGroup grp = (ViewGroup)view; 674 final int N = grp.getChildCount(); 675 if (N <= 0) { 676 return; 677 } 678 prefix = prefix + " "; 679 for (int i=0; i<N; i++) { 680 dumpViewHierarchy(prefix, writer, grp.getChildAt(i)); 681 } 682 } 683 684 void doReallyStop(boolean retaining) { 685 if (!mReallyStopped) { 686 mReallyStopped = true; 687 mRetaining = retaining; 688 mHandler.removeMessages(MSG_REALLY_STOPPED); 689 onReallyStop(); 690 } 691 } 692 693 /** 694 * Pre-HC, we didn't have a way to determine whether an activity was 695 * being stopped for a config change or not until we saw 696 * onRetainNonConfigurationInstance() called after onStop(). However 697 * we need to know this, to know whether to retain fragments. This will 698 * tell us what we need to know. 699 */ 700 void onReallyStop() { 701 mFragments.doLoaderStop(mRetaining); 702 703 mFragments.dispatchReallyStop(); 704 } 705 706 // ------------------------------------------------------------------------ 707 // FRAGMENT SUPPORT 708 // ------------------------------------------------------------------------ 709 710 /** 711 * Called when a fragment is attached to the activity. 712 */ 713 @SuppressWarnings("unused") 714 public void onAttachFragment(Fragment fragment) { 715 } 716 717 /** 718 * Return the FragmentManager for interacting with fragments associated 719 * with this activity. 720 */ 721 public FragmentManager getSupportFragmentManager() { 722 return mFragments.getSupportFragmentManager(); 723 } 724 725 public LoaderManager getSupportLoaderManager() { 726 return mFragments.getSupportLoaderManager(); 727 } 728 729 /** 730 * Modifies the standard behavior to allow results to be delivered to fragments. 731 * This imposes a restriction that requestCode be <= 0xffff. 732 */ 733 @Override 734 public void startActivityForResult(Intent intent, int requestCode) { 735 if (requestCode != -1 && (requestCode&0xffff0000) != 0) { 736 throw new IllegalArgumentException("Can only use lower 16 bits for requestCode"); 737 } 738 super.startActivityForResult(intent, requestCode); 739 } 740 741 /** 742 * Called by Fragment.startActivityForResult() to implement its behavior. 743 */ 744 public void startActivityFromFragment(Fragment fragment, Intent intent, 745 int requestCode) { 746 if (requestCode == -1) { 747 super.startActivityForResult(intent, -1); 748 return; 749 } 750 if ((requestCode&0xffff0000) != 0) { 751 throw new IllegalArgumentException("Can only use lower 16 bits for requestCode"); 752 } 753 super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff)); 754 } 755 756 class HostCallbacks extends FragmentHostCallback<FragmentActivity> { 757 public HostCallbacks() { 758 super(FragmentActivity.this /*fragmentActivity*/); 759 } 760 761 @Override 762 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 763 FragmentActivity.this.dump(prefix, fd, writer, args); 764 } 765 766 @Override 767 public boolean onShouldSaveFragmentState(Fragment fragment) { 768 return !isFinishing(); 769 } 770 771 @Override 772 public LayoutInflater onGetLayoutInflater() { 773 return FragmentActivity.this.getLayoutInflater().cloneInContext(FragmentActivity.this); 774 } 775 776 @Override 777 public FragmentActivity onGetHost() { 778 return FragmentActivity.this; 779 } 780 781 @Override 782 public void onSupportInvalidateOptionsMenu() { 783 FragmentActivity.this.supportInvalidateOptionsMenu(); 784 } 785 786 @Override 787 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode) { 788 FragmentActivity.this.startActivityFromFragment(fragment, intent, requestCode); 789 } 790 791 @Override 792 public boolean onHasWindowAnimations() { 793 return getWindow() != null; 794 } 795 796 @Override 797 public int onGetWindowAnimations() { 798 final Window w = getWindow(); 799 return (w == null) ? 0 : w.getAttributes().windowAnimations; 800 } 801 802 @Override 803 public void onAttachFragment(Fragment fragment) { 804 FragmentActivity.this.onAttachFragment(fragment); 805 } 806 807 @Nullable 808 @Override 809 public View onFindViewById(int id) { 810 return FragmentActivity.this.findViewById(id); 811 } 812 813 @Override 814 public boolean onHasView() { 815 final Window w = getWindow(); 816 return (w != null && w.peekDecorView() != null); 817 } 818 } 819} 820