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 17 package androidx.appcompat.app; 18 19 import android.content.Intent; 20 import android.content.res.Configuration; 21 import android.content.res.Resources; 22 import android.os.Build; 23 import android.os.Bundle; 24 import android.util.DisplayMetrics; 25 import android.view.KeyEvent; 26 import android.view.Menu; 27 import android.view.MenuInflater; 28 import android.view.View; 29 import android.view.ViewGroup; 30 import android.view.Window; 31 32 import androidx.annotation.CallSuper; 33 import androidx.annotation.IdRes; 34 import androidx.annotation.LayoutRes; 35 import androidx.annotation.NonNull; 36 import androidx.annotation.Nullable; 37 import androidx.annotation.StyleRes; 38 import androidx.appcompat.view.ActionMode; 39 import androidx.appcompat.widget.Toolbar; 40 import androidx.appcompat.widget.VectorEnabledTintResources; 41 import androidx.core.app.ActivityCompat; 42 import androidx.core.app.NavUtils; 43 import androidx.core.app.TaskStackBuilder; 44 import androidx.fragment.app.FragmentActivity; 45 46 /** 47 * Base class for activities that use the 48 * <a href="{@docRoot}tools/extras/support-library.html">support library</a> action bar features. 49 * 50 * <p>You can add an {@link androidx.appcompat.app.ActionBar} to your activity when running on API level 7 or higher 51 * by extending this class for your activity and setting the activity theme to 52 * {@link androidx.appcompat.R.style#Theme_AppCompat Theme.AppCompat} or a similar theme. 53 * 54 * <div class="special reference"> 55 * <h3>Developer Guides</h3> 56 * 57 * <p>For information about how to use the action bar, including how to add action items, navigation 58 * modes and more, read the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action 59 * Bar</a> API guide.</p> 60 * </div> 61 */ 62 public class AppCompatActivity extends FragmentActivity implements AppCompatCallback, 63 TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider { 64 65 private AppCompatDelegate mDelegate; 66 private int mThemeId = 0; 67 private Resources mResources; 68 69 @Override onCreate(@ullable Bundle savedInstanceState)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 setTheme(@tyleRes final int resid)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 onPostCreate(@ullable Bundle savedInstanceState)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 getSupportActionBar()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 androidx.appcompat.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 androidx.appcompat.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 */ setSupportActionBar(@ullable Toolbar toolbar)129 public void setSupportActionBar(@Nullable Toolbar toolbar) { 130 getDelegate().setSupportActionBar(toolbar); 131 } 132 133 @Override getMenuInflater()134 public MenuInflater getMenuInflater() { 135 return getDelegate().getMenuInflater(); 136 } 137 138 @Override setContentView(@ayoutRes int layoutResID)139 public void setContentView(@LayoutRes int layoutResID) { 140 getDelegate().setContentView(layoutResID); 141 } 142 143 @Override setContentView(View view)144 public void setContentView(View view) { 145 getDelegate().setContentView(view); 146 } 147 148 @Override setContentView(View view, ViewGroup.LayoutParams params)149 public void setContentView(View view, ViewGroup.LayoutParams params) { 150 getDelegate().setContentView(view, params); 151 } 152 153 @Override addContentView(View view, ViewGroup.LayoutParams params)154 public void addContentView(View view, ViewGroup.LayoutParams params) { 155 getDelegate().addContentView(view, params); 156 } 157 158 @Override onConfigurationChanged(Configuration newConfig)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 onPostResume()171 protected void onPostResume() { 172 super.onPostResume(); 173 getDelegate().onPostResume(); 174 } 175 176 @Override onStart()177 protected void onStart() { 178 super.onStart(); 179 getDelegate().onStart(); 180 } 181 182 @Override onStop()183 protected void onStop() { 184 super.onStop(); 185 getDelegate().onStop(); 186 } 187 188 @SuppressWarnings("TypeParameterUnusedInFormals") 189 @Override findViewById(@dRes int id)190 public <T extends View> T findViewById(@IdRes int id) { 191 return getDelegate().findViewById(id); 192 } 193 194 @Override onMenuItemSelected(int featureId, android.view.MenuItem item)195 public final boolean onMenuItemSelected(int featureId, android.view.MenuItem item) { 196 if (super.onMenuItemSelected(featureId, item)) { 197 return true; 198 } 199 200 final ActionBar ab = getSupportActionBar(); 201 if (item.getItemId() == android.R.id.home && ab != null && 202 (ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) { 203 return onSupportNavigateUp(); 204 } 205 return false; 206 } 207 208 @Override onDestroy()209 protected void onDestroy() { 210 super.onDestroy(); 211 getDelegate().onDestroy(); 212 } 213 214 @Override onTitleChanged(CharSequence title, int color)215 protected void onTitleChanged(CharSequence title, int color) { 216 super.onTitleChanged(title, color); 217 getDelegate().setTitle(title); 218 } 219 220 /** 221 * Enable extended support library window features. 222 * <p> 223 * This is a convenience for calling 224 * {@link android.view.Window#requestFeature getWindow().requestFeature()}. 225 * </p> 226 * 227 * @param featureId The desired feature as defined in 228 * {@link android.view.Window} or {@link androidx.core.view.WindowCompat}. 229 * @return Returns true if the requested feature is supported and now enabled. 230 * 231 * @see android.app.Activity#requestWindowFeature 232 * @see android.view.Window#requestFeature 233 */ supportRequestWindowFeature(int featureId)234 public boolean supportRequestWindowFeature(int featureId) { 235 return getDelegate().requestWindowFeature(featureId); 236 } 237 238 @Override supportInvalidateOptionsMenu()239 public void supportInvalidateOptionsMenu() { 240 getDelegate().invalidateOptionsMenu(); 241 } 242 243 @Override invalidateOptionsMenu()244 public void invalidateOptionsMenu() { 245 getDelegate().invalidateOptionsMenu(); 246 } 247 248 /** 249 * Notifies the Activity that a support action mode has been started. 250 * Activity subclasses overriding this method should call the superclass implementation. 251 * 252 * @param mode The new action mode. 253 */ 254 @Override 255 @CallSuper onSupportActionModeStarted(@onNull ActionMode mode)256 public void onSupportActionModeStarted(@NonNull ActionMode mode) { 257 } 258 259 /** 260 * Notifies the activity that a support action mode has finished. 261 * Activity subclasses overriding this method should call the superclass implementation. 262 * 263 * @param mode The action mode that just finished. 264 */ 265 @Override 266 @CallSuper onSupportActionModeFinished(@onNull ActionMode mode)267 public void onSupportActionModeFinished(@NonNull ActionMode mode) { 268 } 269 270 /** 271 * Called when a support action mode is being started for this window. Gives the 272 * callback an opportunity to handle the action mode in its own unique and 273 * beautiful way. If this method returns null the system can choose a way 274 * to present the mode or choose not to start the mode at all. 275 * 276 * @param callback Callback to control the lifecycle of this action mode 277 * @return The ActionMode that was started, or null if the system should present it 278 */ 279 @Nullable 280 @Override onWindowStartingSupportActionMode(@onNull ActionMode.Callback callback)281 public ActionMode onWindowStartingSupportActionMode(@NonNull ActionMode.Callback callback) { 282 return null; 283 } 284 285 /** 286 * Start an action mode. 287 * 288 * @param callback Callback that will manage lifecycle events for this context mode 289 * @return The ContextMode that was started, or null if it was canceled 290 */ 291 @Nullable startSupportActionMode(@onNull ActionMode.Callback callback)292 public ActionMode startSupportActionMode(@NonNull ActionMode.Callback callback) { 293 return getDelegate().startSupportActionMode(callback); 294 } 295 296 /** 297 * @deprecated Progress bars are no longer provided in AppCompat. 298 */ 299 @Deprecated setSupportProgressBarVisibility(boolean visible)300 public void setSupportProgressBarVisibility(boolean visible) { 301 } 302 303 /** 304 * @deprecated Progress bars are no longer provided in AppCompat. 305 */ 306 @Deprecated setSupportProgressBarIndeterminateVisibility(boolean visible)307 public void setSupportProgressBarIndeterminateVisibility(boolean visible) { 308 } 309 310 /** 311 * @deprecated Progress bars are no longer provided in AppCompat. 312 */ 313 @Deprecated setSupportProgressBarIndeterminate(boolean indeterminate)314 public void setSupportProgressBarIndeterminate(boolean indeterminate) { 315 } 316 317 /** 318 * @deprecated Progress bars are no longer provided in AppCompat. 319 */ 320 @Deprecated setSupportProgress(int progress)321 public void setSupportProgress(int progress) { 322 } 323 324 /** 325 * Support version of {@link #onCreateNavigateUpTaskStack(android.app.TaskStackBuilder)}. 326 * This method will be called on all platform versions. 327 * 328 * Define the synthetic task stack that will be generated during Up navigation from 329 * a different task. 330 * 331 * <p>The default implementation of this method adds the parent chain of this activity 332 * as specified in the manifest to the supplied {@link androidx.core.app.TaskStackBuilder}. Applications 333 * may choose to override this method to construct the desired task stack in a different 334 * way.</p> 335 * 336 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()} 337 * if {@link #shouldUpRecreateTask(android.content.Intent)} returns true when supplied with the intent 338 * returned by {@link #getParentActivityIntent()}.</p> 339 * 340 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined 341 * by the manifest should override 342 * {@link #onPrepareSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}.</p> 343 * 344 * @param builder An empty TaskStackBuilder - the application should add intents representing 345 * the desired task stack 346 */ onCreateSupportNavigateUpTaskStack(@onNull TaskStackBuilder builder)347 public void onCreateSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { 348 builder.addParentStack(this); 349 } 350 351 /** 352 * Support version of {@link #onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder)}. 353 * This method will be called on all platform versions. 354 * 355 * Prepare the synthetic task stack that will be generated during Up navigation 356 * from a different task. 357 * 358 * <p>This method receives the {@link androidx.core.app.TaskStackBuilder} with the constructed series of 359 * Intents as generated by {@link #onCreateSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}. 360 * If any extra data should be added to these intents before launching the new task, 361 * the application should override this method and add that data here.</p> 362 * 363 * @param builder A TaskStackBuilder that has been populated with Intents by 364 * onCreateNavigateUpTaskStack. 365 */ onPrepareSupportNavigateUpTaskStack(@onNull TaskStackBuilder builder)366 public void onPrepareSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { 367 } 368 369 /** 370 * This method is called whenever the user chooses to navigate Up within your application's 371 * activity hierarchy from the action bar. 372 * 373 * <p>If a parent was specified in the manifest for this activity or an activity-alias to it, 374 * default Up navigation will be handled automatically. See 375 * {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity 376 * along the parent chain requires extra Intent arguments, the Activity subclass 377 * should override the method {@link #onPrepareSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)} 378 * to supply those arguments.</p> 379 * 380 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and 381 * Back Stack</a> from the developer guide and 382 * <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide 383 * for more information about navigating within your app.</p> 384 * 385 * <p>See the {@link androidx.core.app.TaskStackBuilder} class and the Activity methods 386 * {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(android.content.Intent)}, and 387 * {@link #supportNavigateUpTo(android.content.Intent)} for help implementing custom Up navigation.</p> 388 * 389 * @return true if Up navigation completed successfully and this Activity was finished, 390 * false otherwise. 391 */ onSupportNavigateUp()392 public boolean onSupportNavigateUp() { 393 Intent upIntent = getSupportParentActivityIntent(); 394 395 if (upIntent != null) { 396 if (supportShouldUpRecreateTask(upIntent)) { 397 TaskStackBuilder b = TaskStackBuilder.create(this); 398 onCreateSupportNavigateUpTaskStack(b); 399 onPrepareSupportNavigateUpTaskStack(b); 400 b.startActivities(); 401 402 try { 403 ActivityCompat.finishAffinity(this); 404 } catch (IllegalStateException e) { 405 // This can only happen on 4.1+, when we don't have a parent or a result set. 406 // In that case we should just finish(). 407 finish(); 408 } 409 } else { 410 // This activity is part of the application's task, so simply 411 // navigate up to the hierarchical parent activity. 412 supportNavigateUpTo(upIntent); 413 } 414 return true; 415 } 416 return false; 417 } 418 419 /** 420 * Obtain an {@link android.content.Intent} that will launch an explicit target activity 421 * specified by sourceActivity's {@link androidx.core.app.NavUtils#PARENT_ACTIVITY} <meta-data> 422 * element in the application's manifest. If the device is running 423 * Jellybean or newer, the android:parentActivityName attribute will be preferred 424 * if it is present. 425 * 426 * @return a new Intent targeting the defined parent activity of sourceActivity 427 */ 428 @Nullable 429 @Override getSupportParentActivityIntent()430 public Intent getSupportParentActivityIntent() { 431 return NavUtils.getParentActivityIntent(this); 432 } 433 434 /** 435 * Returns true if sourceActivity should recreate the task when navigating 'up' 436 * by using targetIntent. 437 * 438 * <p>If this method returns false the app can trivially call 439 * {@link #supportNavigateUpTo(android.content.Intent)} using the same parameters to correctly perform 440 * up navigation. If this method returns false, the app should synthesize a new task stack 441 * by using {@link androidx.core.app.TaskStackBuilder} or another similar mechanism to perform up navigation.</p> 442 * 443 * @param targetIntent An intent representing the target destination for up navigation 444 * @return true if navigating up should recreate a new task stack, false if the same task 445 * should be used for the destination 446 */ supportShouldUpRecreateTask(@onNull Intent targetIntent)447 public boolean supportShouldUpRecreateTask(@NonNull Intent targetIntent) { 448 return NavUtils.shouldUpRecreateTask(this, targetIntent); 449 } 450 451 /** 452 * Navigate from sourceActivity to the activity specified by upIntent, finishing sourceActivity 453 * in the process. upIntent will have the flag {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} set 454 * by this method, along with any others required for proper up navigation as outlined 455 * in the Android Design Guide. 456 * 457 * <p>This method should be used when performing up navigation from within the same task 458 * as the destination. If up navigation should cross tasks in some cases, see 459 * {@link #supportShouldUpRecreateTask(android.content.Intent)}.</p> 460 * 461 * @param upIntent An intent representing the target destination for up navigation 462 */ supportNavigateUpTo(@onNull Intent upIntent)463 public void supportNavigateUpTo(@NonNull Intent upIntent) { 464 NavUtils.navigateUpTo(this, upIntent); 465 } 466 467 @Override onContentChanged()468 public void onContentChanged() { 469 // Call onSupportContentChanged() for legacy reasons 470 onSupportContentChanged(); 471 } 472 473 /** 474 * @deprecated Use {@link #onContentChanged()} instead. 475 */ 476 @Deprecated onSupportContentChanged()477 public void onSupportContentChanged() { 478 } 479 480 @Nullable 481 @Override getDrawerToggleDelegate()482 public ActionBarDrawerToggle.Delegate getDrawerToggleDelegate() { 483 return getDelegate().getDrawerToggleDelegate(); 484 } 485 486 /** 487 * {@inheritDoc} 488 * 489 * <p>Please note: AppCompat uses its own feature id for the action bar: 490 * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> 491 */ 492 @Override onMenuOpened(int featureId, Menu menu)493 public boolean onMenuOpened(int featureId, Menu menu) { 494 return super.onMenuOpened(featureId, menu); 495 } 496 497 /** 498 * {@inheritDoc} 499 * 500 * <p>Please note: AppCompat uses its own feature id for the action bar: 501 * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> 502 */ 503 @Override onPanelClosed(int featureId, Menu menu)504 public void onPanelClosed(int featureId, Menu menu) { 505 super.onPanelClosed(featureId, menu); 506 } 507 508 @Override onSaveInstanceState(Bundle outState)509 protected void onSaveInstanceState(Bundle outState) { 510 super.onSaveInstanceState(outState); 511 getDelegate().onSaveInstanceState(outState); 512 } 513 514 /** 515 * @return The {@link AppCompatDelegate} being used by this Activity. 516 */ 517 @NonNull getDelegate()518 public AppCompatDelegate getDelegate() { 519 if (mDelegate == null) { 520 mDelegate = AppCompatDelegate.create(this, this); 521 } 522 return mDelegate; 523 } 524 525 @Override dispatchKeyEvent(KeyEvent event)526 public boolean dispatchKeyEvent(KeyEvent event) { 527 // Let support action bars open menus in response to the menu key prioritized over 528 // the window handling it 529 final int keyCode = event.getKeyCode(); 530 final ActionBar actionBar = getSupportActionBar(); 531 if (keyCode == KeyEvent.KEYCODE_MENU 532 && actionBar != null && actionBar.onMenuKeyEvent(event)) { 533 return true; 534 } 535 return super.dispatchKeyEvent(event); 536 } 537 538 @Override getResources()539 public Resources getResources() { 540 if (mResources == null && VectorEnabledTintResources.shouldBeUsed()) { 541 mResources = new VectorEnabledTintResources(this, super.getResources()); 542 } 543 return mResources == null ? super.getResources() : mResources; 544 } 545 546 /** 547 * KeyEvents with non-default modifiers are not dispatched to menu's performShortcut in API 25 548 * or lower. Here, we check if the keypress corresponds to a menuitem's shortcut combination 549 * and perform the corresponding action. 550 */ performMenuItemShortcut(int keycode, KeyEvent event)551 private boolean performMenuItemShortcut(int keycode, KeyEvent event) { 552 if (!(Build.VERSION.SDK_INT >= 26) && !event.isCtrlPressed() 553 && !KeyEvent.metaStateHasNoModifiers(event.getMetaState()) 554 && event.getRepeatCount() == 0 555 && !KeyEvent.isModifierKey(event.getKeyCode())) { 556 final Window currentWindow = getWindow(); 557 if (currentWindow != null && currentWindow.getDecorView() != null) { 558 final View decorView = currentWindow.getDecorView(); 559 if (decorView.dispatchKeyShortcutEvent(event)) { 560 return true; 561 } 562 } 563 } 564 return false; 565 } 566 567 @Override onKeyDown(int keyCode, KeyEvent event)568 public boolean onKeyDown(int keyCode, KeyEvent event) { 569 if (performMenuItemShortcut(keyCode, event)) { 570 return true; 571 } 572 return super.onKeyDown(keyCode, event); 573 } 574 575 @Override openOptionsMenu()576 public void openOptionsMenu() { 577 ActionBar actionBar = getSupportActionBar(); 578 if (getWindow().hasFeature(Window.FEATURE_OPTIONS_PANEL) 579 && (actionBar == null || !actionBar.openOptionsMenu())) { 580 super.openOptionsMenu(); 581 } 582 } 583 584 @Override closeOptionsMenu()585 public void closeOptionsMenu() { 586 ActionBar actionBar = getSupportActionBar(); 587 if (getWindow().hasFeature(Window.FEATURE_OPTIONS_PANEL) 588 && (actionBar == null || !actionBar.closeOptionsMenu())) { 589 super.closeOptionsMenu(); 590 } 591 } 592 } 593