1/* 2 * Copyright (C) 2015 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.v7.app; 18 19import android.content.Intent; 20import android.content.res.Configuration; 21import android.content.res.Resources; 22import android.os.Build; 23import android.os.Bundle; 24import android.support.annotation.CallSuper; 25import android.support.annotation.IdRes; 26import android.support.annotation.LayoutRes; 27import android.support.annotation.NonNull; 28import android.support.annotation.Nullable; 29import android.support.annotation.StyleRes; 30import android.support.v4.app.ActivityCompat; 31import android.support.v4.app.FragmentActivity; 32import android.support.v4.app.NavUtils; 33import android.support.v4.app.TaskStackBuilder; 34import android.support.v4.view.KeyEventCompat; 35import android.support.v7.view.ActionMode; 36import android.support.v7.widget.Toolbar; 37import android.support.v7.widget.VectorEnabledTintResources; 38import android.util.DisplayMetrics; 39import android.view.KeyEvent; 40import android.view.Menu; 41import android.view.MenuInflater; 42import android.view.View; 43import android.view.ViewGroup; 44 45/** 46 * Base class for activities that use the 47 * <a href="{@docRoot}tools/extras/support-library.html">support library</a> action bar features. 48 * 49 * <p>You can add an {@link android.support.v7.app.ActionBar} to your activity when running on API level 7 or higher 50 * by extending this class for your activity and setting the activity theme to 51 * {@link android.support.v7.appcompat.R.style#Theme_AppCompat Theme.AppCompat} or a similar theme. 52 * 53 * <div class="special reference"> 54 * <h3>Developer Guides</h3> 55 * 56 * <p>For information about how to use the action bar, including how to add action items, navigation 57 * modes and more, read the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action 58 * Bar</a> API guide.</p> 59 * </div> 60 */ 61public class AppCompatActivity extends FragmentActivity implements AppCompatCallback, 62 TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider { 63 64 private AppCompatDelegate mDelegate; 65 private int mThemeId = 0; 66 private boolean mEatKeyUpEvent; 67 private Resources mResources; 68 69 @Override 70 protected void onCreate(@Nullable Bundle savedInstanceState) { 71 final AppCompatDelegate delegate = getDelegate(); 72 delegate.installViewFactory(); 73 delegate.onCreate(savedInstanceState); 74 if (delegate.applyDayNight() && mThemeId != 0) { 75 // If DayNight has been applied, we need to re-apply the theme for 76 // the changes to take effect. On API 23+, we should bypass 77 // setTheme(), which will no-op if the theme ID is identical to the 78 // current theme ID. 79 if (Build.VERSION.SDK_INT >= 23) { 80 onApplyThemeResource(getTheme(), mThemeId, false); 81 } else { 82 setTheme(mThemeId); 83 } 84 } 85 super.onCreate(savedInstanceState); 86 } 87 88 @Override 89 public void setTheme(@StyleRes final int resid) { 90 super.setTheme(resid); 91 // Keep hold of the theme id so that we can re-set it later if needed 92 mThemeId = resid; 93 } 94 95 @Override 96 protected void onPostCreate(@Nullable Bundle savedInstanceState) { 97 super.onPostCreate(savedInstanceState); 98 getDelegate().onPostCreate(savedInstanceState); 99 } 100 101 /** 102 * Support library version of {@link android.app.Activity#getActionBar}. 103 * 104 * <p>Retrieve a reference to this activity's ActionBar. 105 * 106 * @return The Activity's ActionBar, or null if it does not have one. 107 */ 108 @Nullable 109 public ActionBar getSupportActionBar() { 110 return getDelegate().getSupportActionBar(); 111 } 112 113 /** 114 * Set a {@link android.widget.Toolbar Toolbar} to act as the 115 * {@link android.support.v7.app.ActionBar} for this Activity window. 116 * 117 * <p>When set to a non-null value the {@link #getActionBar()} method will return 118 * an {@link android.support.v7.app.ActionBar} object that can be used to control the given 119 * toolbar as if it were a traditional window decor action bar. The toolbar's menu will be 120 * populated with the Activity's options menu and the navigation button will be wired through 121 * the standard {@link android.R.id#home home} menu select action.</p> 122 * 123 * <p>In order to use a Toolbar within the Activity's window content the application 124 * must not request the window feature 125 * {@link android.view.Window#FEATURE_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> 126 * 127 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it 128 */ 129 public void setSupportActionBar(@Nullable Toolbar toolbar) { 130 getDelegate().setSupportActionBar(toolbar); 131 } 132 133 @Override 134 public MenuInflater getMenuInflater() { 135 return getDelegate().getMenuInflater(); 136 } 137 138 @Override 139 public void setContentView(@LayoutRes int layoutResID) { 140 getDelegate().setContentView(layoutResID); 141 } 142 143 @Override 144 public void setContentView(View view) { 145 getDelegate().setContentView(view); 146 } 147 148 @Override 149 public void setContentView(View view, ViewGroup.LayoutParams params) { 150 getDelegate().setContentView(view, params); 151 } 152 153 @Override 154 public void addContentView(View view, ViewGroup.LayoutParams params) { 155 getDelegate().addContentView(view, params); 156 } 157 158 @Override 159 public void onConfigurationChanged(Configuration newConfig) { 160 super.onConfigurationChanged(newConfig); 161 getDelegate().onConfigurationChanged(newConfig); 162 if (mResources != null) { 163 // The real (and thus managed) resources object was already updated 164 // by ResourcesManager, so pull the current metrics from there. 165 final DisplayMetrics newMetrics = super.getResources().getDisplayMetrics(); 166 mResources.updateConfiguration(newConfig, newMetrics); 167 } 168 } 169 170 @Override 171 protected void onStop() { 172 super.onStop(); 173 getDelegate().onStop(); 174 } 175 176 @Override 177 protected void onPostResume() { 178 super.onPostResume(); 179 getDelegate().onPostResume(); 180 } 181 182 public View findViewById(@IdRes int id) { 183 return getDelegate().findViewById(id); 184 } 185 186 @Override 187 public final boolean onMenuItemSelected(int featureId, android.view.MenuItem item) { 188 if (super.onMenuItemSelected(featureId, item)) { 189 return true; 190 } 191 192 final ActionBar ab = getSupportActionBar(); 193 if (item.getItemId() == android.R.id.home && ab != null && 194 (ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) { 195 return onSupportNavigateUp(); 196 } 197 return false; 198 } 199 200 @Override 201 protected void onDestroy() { 202 super.onDestroy(); 203 getDelegate().onDestroy(); 204 } 205 206 @Override 207 protected void onTitleChanged(CharSequence title, int color) { 208 super.onTitleChanged(title, color); 209 getDelegate().setTitle(title); 210 } 211 212 /** 213 * Enable extended support library window features. 214 * <p> 215 * This is a convenience for calling 216 * {@link android.view.Window#requestFeature getWindow().requestFeature()}. 217 * </p> 218 * 219 * @param featureId The desired feature as defined in 220 * {@link android.view.Window} or {@link android.support.v4.view.WindowCompat}. 221 * @return Returns true if the requested feature is supported and now enabled. 222 * 223 * @see android.app.Activity#requestWindowFeature 224 * @see android.view.Window#requestFeature 225 */ 226 public boolean supportRequestWindowFeature(int featureId) { 227 return getDelegate().requestWindowFeature(featureId); 228 } 229 230 @Override 231 public void supportInvalidateOptionsMenu() { 232 getDelegate().invalidateOptionsMenu(); 233 } 234 235 /** 236 * @hide 237 */ 238 public void invalidateOptionsMenu() { 239 getDelegate().invalidateOptionsMenu(); 240 } 241 242 /** 243 * Notifies the Activity that a support action mode has been started. 244 * Activity subclasses overriding this method should call the superclass implementation. 245 * 246 * @param mode The new action mode. 247 */ 248 @CallSuper 249 public void onSupportActionModeStarted(@NonNull ActionMode mode) { 250 } 251 252 /** 253 * Notifies the activity that a support action mode has finished. 254 * Activity subclasses overriding this method should call the superclass implementation. 255 * 256 * @param mode The action mode that just finished. 257 */ 258 @CallSuper 259 public void onSupportActionModeFinished(@NonNull ActionMode mode) { 260 } 261 262 /** 263 * Called when a support action mode is being started for this window. Gives the 264 * callback an opportunity to handle the action mode in its own unique and 265 * beautiful way. If this method returns null the system can choose a way 266 * to present the mode or choose not to start the mode at all. 267 * 268 * @param callback Callback to control the lifecycle of this action mode 269 * @return The ActionMode that was started, or null if the system should present it 270 */ 271 @Nullable 272 @Override 273 public ActionMode onWindowStartingSupportActionMode(@NonNull ActionMode.Callback callback) { 274 return null; 275 } 276 277 /** 278 * Start an action mode. 279 * 280 * @param callback Callback that will manage lifecycle events for this context mode 281 * @return The ContextMode that was started, or null if it was canceled 282 */ 283 @Nullable 284 public ActionMode startSupportActionMode(@NonNull ActionMode.Callback callback) { 285 return getDelegate().startSupportActionMode(callback); 286 } 287 288 /** 289 * @deprecated Progress bars are no longer provided in AppCompat. 290 */ 291 @Deprecated 292 public void setSupportProgressBarVisibility(boolean visible) { 293 } 294 295 /** 296 * @deprecated Progress bars are no longer provided in AppCompat. 297 */ 298 @Deprecated 299 public void setSupportProgressBarIndeterminateVisibility(boolean visible) { 300 } 301 302 /** 303 * @deprecated Progress bars are no longer provided in AppCompat. 304 */ 305 @Deprecated 306 public void setSupportProgressBarIndeterminate(boolean indeterminate) { 307 } 308 309 /** 310 * @deprecated Progress bars are no longer provided in AppCompat. 311 */ 312 @Deprecated 313 public void setSupportProgress(int progress) { 314 } 315 316 /** 317 * Support version of {@link #onCreateNavigateUpTaskStack(android.app.TaskStackBuilder)}. 318 * This method will be called on all platform versions. 319 * 320 * Define the synthetic task stack that will be generated during Up navigation from 321 * a different task. 322 * 323 * <p>The default implementation of this method adds the parent chain of this activity 324 * as specified in the manifest to the supplied {@link android.support.v4.app.TaskStackBuilder}. Applications 325 * may choose to override this method to construct the desired task stack in a different 326 * way.</p> 327 * 328 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()} 329 * if {@link #shouldUpRecreateTask(android.content.Intent)} returns true when supplied with the intent 330 * returned by {@link #getParentActivityIntent()}.</p> 331 * 332 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined 333 * by the manifest should override 334 * {@link #onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}.</p> 335 * 336 * @param builder An empty TaskStackBuilder - the application should add intents representing 337 * the desired task stack 338 */ 339 public void onCreateSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { 340 builder.addParentStack(this); 341 } 342 343 /** 344 * Support version of {@link #onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder)}. 345 * This method will be called on all platform versions. 346 * 347 * Prepare the synthetic task stack that will be generated during Up navigation 348 * from a different task. 349 * 350 * <p>This method receives the {@link android.support.v4.app.TaskStackBuilder} with the constructed series of 351 * Intents as generated by {@link #onCreateSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}. 352 * If any extra data should be added to these intents before launching the new task, 353 * the application should override this method and add that data here.</p> 354 * 355 * @param builder A TaskStackBuilder that has been populated with Intents by 356 * onCreateNavigateUpTaskStack. 357 */ 358 public void onPrepareSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { 359 } 360 361 /** 362 * This method is called whenever the user chooses to navigate Up within your application's 363 * activity hierarchy from the action bar. 364 * 365 * <p>If a parent was specified in the manifest for this activity or an activity-alias to it, 366 * default Up navigation will be handled automatically. See 367 * {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity 368 * along the parent chain requires extra Intent arguments, the Activity subclass 369 * should override the method {@link #onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)} 370 * to supply those arguments.</p> 371 * 372 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and 373 * Back Stack</a> from the developer guide and 374 * <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide 375 * for more information about navigating within your app.</p> 376 * 377 * <p>See the {@link android.support.v4.app.TaskStackBuilder} class and the Activity methods 378 * {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(android.content.Intent)}, and 379 * {@link #supportNavigateUpTo(android.content.Intent)} for help implementing custom Up navigation.</p> 380 * 381 * @return true if Up navigation completed successfully and this Activity was finished, 382 * false otherwise. 383 */ 384 public boolean onSupportNavigateUp() { 385 Intent upIntent = getSupportParentActivityIntent(); 386 387 if (upIntent != null) { 388 if (supportShouldUpRecreateTask(upIntent)) { 389 TaskStackBuilder b = TaskStackBuilder.create(this); 390 onCreateSupportNavigateUpTaskStack(b); 391 onPrepareSupportNavigateUpTaskStack(b); 392 b.startActivities(); 393 394 try { 395 ActivityCompat.finishAffinity(this); 396 } catch (IllegalStateException e) { 397 // This can only happen on 4.1+, when we don't have a parent or a result set. 398 // In that case we should just finish(). 399 finish(); 400 } 401 } else { 402 // This activity is part of the application's task, so simply 403 // navigate up to the hierarchical parent activity. 404 supportNavigateUpTo(upIntent); 405 } 406 return true; 407 } 408 return false; 409 } 410 411 /** 412 * Obtain an {@link android.content.Intent} that will launch an explicit target activity 413 * specified by sourceActivity's {@link android.support.v4.app.NavUtils#PARENT_ACTIVITY} <meta-data> 414 * element in the application's manifest. If the device is running 415 * Jellybean or newer, the android:parentActivityName attribute will be preferred 416 * if it is present. 417 * 418 * @return a new Intent targeting the defined parent activity of sourceActivity 419 */ 420 @Nullable 421 public Intent getSupportParentActivityIntent() { 422 return NavUtils.getParentActivityIntent(this); 423 } 424 425 /** 426 * Returns true if sourceActivity should recreate the task when navigating 'up' 427 * by using targetIntent. 428 * 429 * <p>If this method returns false the app can trivially call 430 * {@link #supportNavigateUpTo(android.content.Intent)} using the same parameters to correctly perform 431 * up navigation. If this method returns false, the app should synthesize a new task stack 432 * by using {@link android.support.v4.app.TaskStackBuilder} or another similar mechanism to perform up navigation.</p> 433 * 434 * @param targetIntent An intent representing the target destination for up navigation 435 * @return true if navigating up should recreate a new task stack, false if the same task 436 * should be used for the destination 437 */ 438 public boolean supportShouldUpRecreateTask(@NonNull Intent targetIntent) { 439 return NavUtils.shouldUpRecreateTask(this, targetIntent); 440 } 441 442 /** 443 * Navigate from sourceActivity to the activity specified by upIntent, finishing sourceActivity 444 * in the process. upIntent will have the flag {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} set 445 * by this method, along with any others required for proper up navigation as outlined 446 * in the Android Design Guide. 447 * 448 * <p>This method should be used when performing up navigation from within the same task 449 * as the destination. If up navigation should cross tasks in some cases, see 450 * {@link #supportShouldUpRecreateTask(android.content.Intent)}.</p> 451 * 452 * @param upIntent An intent representing the target destination for up navigation 453 */ 454 public void supportNavigateUpTo(@NonNull Intent upIntent) { 455 NavUtils.navigateUpTo(this, upIntent); 456 } 457 458 @Override 459 public void onContentChanged() { 460 // Call onSupportContentChanged() for legacy reasons 461 onSupportContentChanged(); 462 } 463 464 /** 465 * @deprecated Use {@link #onContentChanged()} instead. 466 */ 467 @Deprecated 468 public void onSupportContentChanged() { 469 } 470 471 @Nullable 472 @Override 473 public ActionBarDrawerToggle.Delegate getDrawerToggleDelegate() { 474 return getDelegate().getDrawerToggleDelegate(); 475 } 476 477 /** 478 * {@inheritDoc} 479 * 480 * <p>Please note: AppCompat uses it's own feature id for the action bar: 481 * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> 482 */ 483 @Override 484 public boolean onMenuOpened(int featureId, Menu menu) { 485 return super.onMenuOpened(featureId, menu); 486 } 487 488 /** 489 * {@inheritDoc} 490 * 491 * <p>Please note: AppCompat uses it's own feature id for the action bar: 492 * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> 493 */ 494 @Override 495 public void onPanelClosed(int featureId, Menu menu) { 496 super.onPanelClosed(featureId, menu); 497 } 498 499 @Override 500 protected void onSaveInstanceState(Bundle outState) { 501 super.onSaveInstanceState(outState); 502 getDelegate().onSaveInstanceState(outState); 503 } 504 505 /** 506 * @return The {@link AppCompatDelegate} being used by this Activity. 507 */ 508 @NonNull 509 public AppCompatDelegate getDelegate() { 510 if (mDelegate == null) { 511 mDelegate = AppCompatDelegate.create(this, this); 512 } 513 return mDelegate; 514 } 515 516 @Override 517 public boolean dispatchKeyEvent(KeyEvent event) { 518 if (KeyEventCompat.isCtrlPressed(event) && 519 event.getUnicodeChar(event.getMetaState() & ~KeyEvent.META_CTRL_MASK) == '<') { 520 // Capture the Control-< and send focus to the ActionBar 521 final int action = event.getAction(); 522 if (action == KeyEvent.ACTION_DOWN) { 523 final ActionBar actionBar = getSupportActionBar(); 524 if (actionBar != null && actionBar.isShowing() && actionBar.requestFocus()) { 525 mEatKeyUpEvent = true; 526 return true; 527 } 528 } else if (action == KeyEvent.ACTION_UP && mEatKeyUpEvent) { 529 mEatKeyUpEvent = false; 530 return true; 531 } 532 } 533 return super.dispatchKeyEvent(event); 534 } 535 536 @Override 537 public Resources getResources() { 538 if (mResources == null && VectorEnabledTintResources.shouldBeUsed()) { 539 mResources = new VectorEnabledTintResources(this, super.getResources()); 540 } 541 return mResources == null ? super.getResources() : mResources; 542 } 543} 544