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.Context;
20 import android.content.Intent;
21 import android.content.res.Configuration;
22 import android.content.res.Resources;
23 import android.os.Build;
24 import android.os.Bundle;
25 import android.util.DisplayMetrics;
26 import android.view.KeyEvent;
27 import android.view.Menu;
28 import android.view.MenuInflater;
29 import android.view.View;
30 import android.view.ViewGroup;
31 import android.view.Window;
32 
33 import androidx.activity.ViewTreeOnBackPressedDispatcherOwner;
34 import androidx.activity.contextaware.OnContextAvailableListener;
35 import androidx.annotation.CallSuper;
36 import androidx.annotation.ContentView;
37 import androidx.annotation.IdRes;
38 import androidx.annotation.LayoutRes;
39 import androidx.annotation.StyleRes;
40 import androidx.appcompat.app.AppCompatDelegate.NightMode;
41 import androidx.appcompat.view.ActionMode;
42 import androidx.appcompat.widget.Toolbar;
43 import androidx.appcompat.widget.VectorEnabledTintResources;
44 import androidx.core.app.ActivityCompat;
45 import androidx.core.app.NavUtils;
46 import androidx.core.app.TaskStackBuilder;
47 import androidx.core.os.LocaleListCompat;
48 import androidx.fragment.app.FragmentActivity;
49 import androidx.lifecycle.ViewTreeLifecycleOwner;
50 import androidx.lifecycle.ViewTreeViewModelStoreOwner;
51 import androidx.savedstate.SavedStateRegistry;
52 import androidx.savedstate.ViewTreeSavedStateRegistryOwner;
53 
54 import org.jspecify.annotations.NonNull;
55 import org.jspecify.annotations.Nullable;
56 
57 /**
58  * Base class for activities that wish to use some of the newer platform features on older
59  * Android devices. Some of these backported features include:
60  *
61  * <ul>
62  *     <li>Using the action bar, including action items, navigation modes and more with
63  *     the {@link #setSupportActionBar(Toolbar)} API.</li>
64  *     <li>Built-in switching between light and dark themes by using the
65  *     {@link androidx.appcompat.R.style#Theme_AppCompat_DayNight Theme.AppCompat.DayNight} theme
66  *     and {@link AppCompatDelegate#setDefaultNightMode(int)} API.</li>
67  *     <li>Integration with <code>DrawerLayout</code> by using the
68  *     {@link #getDrawerToggleDelegate()} API.</li>
69  * </ul>
70  *
71  * <p>Note that every activity that extends this class has to be themed with
72  * {@link androidx.appcompat.R.style#Theme_AppCompat Theme.AppCompat} or a theme that extends
73  * that theme.</p>
74  *
75  * <div class="special reference">
76  * <h3>Developer Guides</h3>
77  *
78  * <p>For information about how to use the action bar, including how to add action items, navigation
79  * modes and more, read the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action
80  * Bar</a> API guide.</p>
81  * </div>
82  */
83 public class AppCompatActivity extends FragmentActivity implements AppCompatCallback,
84         TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {
85 
86     private static final String DELEGATE_TAG = "androidx:appcompat";
87 
88     private AppCompatDelegate mDelegate;
89     private Resources mResources;
90 
91     /**
92      * Default constructor for AppCompatActivity. All Activities must have a default constructor
93      * for API 27 and lower devices or when using the default
94      * {@link android.app.AppComponentFactory}.
95      */
AppCompatActivity()96     public AppCompatActivity() {
97         super();
98         initDelegate();
99     }
100 
101     /**
102      * Alternate constructor that can be used to provide a default layout
103      * that will be inflated as part of <code>super.onCreate(savedInstanceState)</code>.
104      *
105      * <p>This should generally be called from your constructor that takes no parameters,
106      * as is required for API 27 and lower or when using the default
107      * {@link android.app.AppComponentFactory}.
108      *
109      * @see #AppCompatActivity()
110      */
111     @ContentView
AppCompatActivity(@ayoutRes int contentLayoutId)112     public AppCompatActivity(@LayoutRes int contentLayoutId) {
113         super(contentLayoutId);
114         initDelegate();
115     }
116 
initDelegate()117     private void initDelegate() {
118         // TODO: Directly connect AppCompatDelegate to SavedStateRegistry
119         getSavedStateRegistry().registerSavedStateProvider(DELEGATE_TAG,
120                 new SavedStateRegistry.SavedStateProvider() {
121                     @Override
122                     public @NonNull Bundle saveState() {
123                         Bundle outState = new Bundle();
124                         getDelegate().onSaveInstanceState(outState);
125                         return outState;
126                     }
127                 });
128         addOnContextAvailableListener(new OnContextAvailableListener() {
129             @Override
130             public void onContextAvailable(@NonNull Context context) {
131                 final AppCompatDelegate delegate = getDelegate();
132                 delegate.installViewFactory();
133                 delegate.onCreate(getSavedStateRegistry()
134                         .consumeRestoredStateForKey(DELEGATE_TAG));
135             }
136         });
137     }
138 
139     @Override
attachBaseContext(Context newBase)140     protected void attachBaseContext(Context newBase) {
141         super.attachBaseContext(getDelegate().attachBaseContext2(newBase));
142     }
143 
144     @Override
setTheme(@tyleRes final int resId)145     public void setTheme(@StyleRes final int resId) {
146         super.setTheme(resId);
147         getDelegate().setTheme(resId);
148     }
149 
150     @Override
onPostCreate(@ullable Bundle savedInstanceState)151     protected void onPostCreate(@Nullable Bundle savedInstanceState) {
152         super.onPostCreate(savedInstanceState);
153         getDelegate().onPostCreate(savedInstanceState);
154     }
155 
156     /**
157      * Support library version of {@link android.app.Activity#getActionBar}.
158      *
159      * <p>Retrieve a reference to this activity's ActionBar.
160      *
161      * @return The Activity's ActionBar, or null if it does not have one.
162      */
getSupportActionBar()163     public @Nullable ActionBar getSupportActionBar() {
164         return getDelegate().getSupportActionBar();
165     }
166 
167     /**
168      * Set a {@link android.widget.Toolbar Toolbar} to act as the
169      * {@link androidx.appcompat.app.ActionBar} for this Activity window.
170      *
171      * <p>When set to a non-null value the {@link #getActionBar()} method will return
172      * an {@link androidx.appcompat.app.ActionBar} object that can be used to control the given
173      * toolbar as if it were a traditional window decor action bar. The toolbar's menu will be
174      * populated with the Activity's options menu and the navigation button will be wired through
175      * the standard {@link android.R.id#home home} menu select action.</p>
176      *
177      * <p>In order to use a Toolbar within the Activity's window content the application
178      * must not request the window feature
179      * {@link android.view.Window#FEATURE_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p>
180      *
181      * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
182      */
setSupportActionBar(@ullable Toolbar toolbar)183     public void setSupportActionBar(@Nullable Toolbar toolbar) {
184         getDelegate().setSupportActionBar(toolbar);
185     }
186 
187     @Override
getMenuInflater()188     public @NonNull MenuInflater getMenuInflater() {
189         return getDelegate().getMenuInflater();
190     }
191 
192     @Override
setContentView(@ayoutRes int layoutResID)193     public void setContentView(@LayoutRes int layoutResID) {
194         initViewTreeOwners();
195         getDelegate().setContentView(layoutResID);
196     }
197 
198     @Override
setContentView(View view)199     public void setContentView(View view) {
200         initViewTreeOwners();
201         getDelegate().setContentView(view);
202     }
203 
204     @Override
setContentView(View view, ViewGroup.LayoutParams params)205     public void setContentView(View view, ViewGroup.LayoutParams params) {
206         initViewTreeOwners();
207         getDelegate().setContentView(view, params);
208     }
209 
210     @Override
addContentView(View view, ViewGroup.LayoutParams params)211     public void addContentView(View view, ViewGroup.LayoutParams params) {
212         initViewTreeOwners();
213         getDelegate().addContentView(view, params);
214     }
215 
initViewTreeOwners()216     private void initViewTreeOwners() {
217         // Set the view tree owners before setting the content view so that the inflation process
218         // and attach listeners will see them already present
219         ViewTreeLifecycleOwner.set(getWindow().getDecorView(), this);
220         ViewTreeViewModelStoreOwner.set(getWindow().getDecorView(), this);
221         ViewTreeSavedStateRegistryOwner.set(getWindow().getDecorView(), this);
222         ViewTreeOnBackPressedDispatcherOwner.set(getWindow().getDecorView(), this);
223     }
224 
225     @Override
onConfigurationChanged(@onNull Configuration newConfig)226     public void onConfigurationChanged(@NonNull Configuration newConfig) {
227         super.onConfigurationChanged(newConfig);
228 
229         // The delegate may modify the real resources object or the config param to implement its
230         // desired configuration overrides. Let it do it's thing and then use the resulting state.
231         getDelegate().onConfigurationChanged(newConfig);
232 
233         // Manually propagate configuration changes to our unmanaged resources object.
234         if (mResources != null) {
235             final Configuration currConfig = super.getResources().getConfiguration();
236             final DisplayMetrics currMetrics = super.getResources().getDisplayMetrics();
237             mResources.updateConfiguration(currConfig, currMetrics);
238         }
239     }
240 
241     @Override
onPostResume()242     protected void onPostResume() {
243         super.onPostResume();
244         getDelegate().onPostResume();
245     }
246 
247     @Override
onStart()248     protected void onStart() {
249         super.onStart();
250         getDelegate().onStart();
251     }
252 
253     @Override
onStop()254     protected void onStop() {
255         super.onStop();
256         getDelegate().onStop();
257     }
258 
259     @SuppressWarnings("TypeParameterUnusedInFormals")
260     @Override
findViewById(@dRes int id)261     public <T extends View> T findViewById(@IdRes int id) {
262         return getDelegate().findViewById(id);
263     }
264 
265     @Override
onMenuItemSelected(int featureId, android.view.@NonNull MenuItem item)266     public final boolean onMenuItemSelected(int featureId, android.view.@NonNull MenuItem item) {
267         if (super.onMenuItemSelected(featureId, item)) {
268             return true;
269         }
270 
271         final ActionBar ab = getSupportActionBar();
272         if (item.getItemId() == android.R.id.home && ab != null &&
273                 (ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
274             return onSupportNavigateUp();
275         }
276         return false;
277     }
278 
279     @Override
onDestroy()280     protected void onDestroy() {
281         super.onDestroy();
282         getDelegate().onDestroy();
283     }
284 
285     @Override
onTitleChanged(CharSequence title, int color)286     protected void onTitleChanged(CharSequence title, int color) {
287         super.onTitleChanged(title, color);
288         getDelegate().setTitle(title);
289     }
290 
291     /**
292      * Enable extended support library window features.
293      * <p>
294      * This is a convenience for calling
295      * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
296      * </p>
297      *
298      * @param featureId The desired feature as defined in
299      * {@link android.view.Window} or {@link androidx.core.view.WindowCompat}.
300      * @return Returns true if the requested feature is supported and now enabled.
301      *
302      * @see android.app.Activity#requestWindowFeature
303      * @see android.view.Window#requestFeature
304      */
supportRequestWindowFeature(int featureId)305     public boolean supportRequestWindowFeature(int featureId) {
306         return getDelegate().requestWindowFeature(featureId);
307     }
308 
309     @SuppressWarnings("deprecation")
310     @Override
supportInvalidateOptionsMenu()311     public void supportInvalidateOptionsMenu() {
312         getDelegate().invalidateOptionsMenu();
313     }
314 
315     @Override
invalidateOptionsMenu()316     public void invalidateOptionsMenu() {
317         getDelegate().invalidateOptionsMenu();
318     }
319 
320     /**
321      * Notifies the Activity that a support action mode has been started.
322      * Activity subclasses overriding this method should call the superclass implementation.
323      *
324      * @param mode The new action mode.
325      */
326     @Override
327     @CallSuper
onSupportActionModeStarted(@onNull ActionMode mode)328     public void onSupportActionModeStarted(@NonNull ActionMode mode) {
329     }
330 
331     /**
332      * Notifies the activity that a support action mode has finished.
333      * Activity subclasses overriding this method should call the superclass implementation.
334      *
335      * @param mode The action mode that just finished.
336      */
337     @Override
338     @CallSuper
onSupportActionModeFinished(@onNull ActionMode mode)339     public void onSupportActionModeFinished(@NonNull ActionMode mode) {
340     }
341 
342     /**
343      * Called when a support action mode is being started for this window. Gives the
344      * callback an opportunity to handle the action mode in its own unique and
345      * beautiful way. If this method returns null the system can choose a way
346      * to present the mode or choose not to start the mode at all.
347      *
348      * @param callback Callback to control the lifecycle of this action mode
349      * @return The ActionMode that was started, or null if the system should present it
350      */
351     @Override
onWindowStartingSupportActionMode( ActionMode.@onNull Callback callback)352     public @Nullable ActionMode onWindowStartingSupportActionMode(
353             ActionMode.@NonNull Callback callback) {
354         return null;
355     }
356 
357     /**
358      * Start an action mode.
359      *
360      * @param callback Callback that will manage lifecycle events for this context mode
361      * @return The ContextMode that was started, or null if it was canceled
362      */
startSupportActionMode(ActionMode.@onNull Callback callback)363     public @Nullable ActionMode startSupportActionMode(ActionMode.@NonNull Callback callback) {
364         return getDelegate().startSupportActionMode(callback);
365     }
366 
367     /**
368      * @deprecated Progress bars are no longer provided in AppCompat.
369      */
370     @Deprecated
setSupportProgressBarVisibility(boolean visible)371     public void setSupportProgressBarVisibility(boolean visible) {
372     }
373 
374     /**
375      * @deprecated Progress bars are no longer provided in AppCompat.
376      */
377     @Deprecated
setSupportProgressBarIndeterminateVisibility(boolean visible)378     public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
379     }
380 
381     /**
382      * @deprecated Progress bars are no longer provided in AppCompat.
383      */
384     @Deprecated
setSupportProgressBarIndeterminate(boolean indeterminate)385     public void setSupportProgressBarIndeterminate(boolean indeterminate) {
386     }
387 
388     /**
389      * @deprecated Progress bars are no longer provided in AppCompat.
390      */
391     @Deprecated
setSupportProgress(int progress)392     public void setSupportProgress(int progress) {
393     }
394 
395     /**
396      * Support version of {@link #onCreateNavigateUpTaskStack(android.app.TaskStackBuilder)}.
397      * This method will be called on all platform versions.
398      *
399      * Define the synthetic task stack that will be generated during Up navigation from
400      * a different task.
401      *
402      * <p>The default implementation of this method adds the parent chain of this activity
403      * as specified in the manifest to the supplied {@link androidx.core.app.TaskStackBuilder}. Applications
404      * may choose to override this method to construct the desired task stack in a different
405      * way.</p>
406      *
407      * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
408      * if {@link #shouldUpRecreateTask(android.content.Intent)} returns true when supplied with the intent
409      * returned by {@link #getParentActivityIntent()}.</p>
410      *
411      * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
412      * by the manifest should override
413      * {@link #onPrepareSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}.</p>
414      *
415      * @param builder An empty TaskStackBuilder - the application should add intents representing
416      *                the desired task stack
417      */
onCreateSupportNavigateUpTaskStack(@onNull TaskStackBuilder builder)418     public void onCreateSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) {
419         builder.addParentStack(this);
420     }
421 
422     /**
423      * Support version of {@link #onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder)}.
424      * This method will be called on all platform versions.
425      *
426      * Prepare the synthetic task stack that will be generated during Up navigation
427      * from a different task.
428      *
429      * <p>This method receives the {@link androidx.core.app.TaskStackBuilder} with the constructed series of
430      * Intents as generated by {@link #onCreateSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}.
431      * If any extra data should be added to these intents before launching the new task,
432      * the application should override this method and add that data here.</p>
433      *
434      * @param builder A TaskStackBuilder that has been populated with Intents by
435      *                onCreateNavigateUpTaskStack.
436      */
onPrepareSupportNavigateUpTaskStack(@onNull TaskStackBuilder builder)437     public void onPrepareSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) {
438     }
439 
440     /**
441      * This method is called whenever the user chooses to navigate Up within your application's
442      * activity hierarchy from the action bar.
443      *
444      * <p>If a parent was specified in the manifest for this activity or an activity-alias to it,
445      * default Up navigation will be handled automatically. See
446      * {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity
447      * along the parent chain requires extra Intent arguments, the Activity subclass
448      * should override the method {@link #onPrepareSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}
449      * to supply those arguments.</p>
450      *
451      * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and
452      * Back Stack</a> from the developer guide and
453      * <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide
454      * for more information about navigating within your app.</p>
455      *
456      * <p>See the {@link androidx.core.app.TaskStackBuilder} class and the Activity methods
457      * {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(android.content.Intent)}, and
458      * {@link #supportNavigateUpTo(android.content.Intent)} for help implementing custom Up navigation.</p>
459      *
460      * @return true if Up navigation completed successfully and this Activity was finished,
461      *         false otherwise.
462      */
onSupportNavigateUp()463     public boolean onSupportNavigateUp() {
464         Intent upIntent = getSupportParentActivityIntent();
465 
466         if (upIntent != null) {
467             if (supportShouldUpRecreateTask(upIntent)) {
468                 TaskStackBuilder b = TaskStackBuilder.create(this);
469                 onCreateSupportNavigateUpTaskStack(b);
470                 onPrepareSupportNavigateUpTaskStack(b);
471                 b.startActivities();
472 
473                 try {
474                     ActivityCompat.finishAffinity(this);
475                 } catch (IllegalStateException e) {
476                     // This can only happen on 4.1+, when we don't have a parent or a result set.
477                     // In that case we should just finish().
478                     finish();
479                 }
480             } else {
481                 // This activity is part of the application's task, so simply
482                 // navigate up to the hierarchical parent activity.
483                 supportNavigateUpTo(upIntent);
484             }
485             return true;
486         }
487         return false;
488     }
489 
490     /**
491      * Obtain an {@link android.content.Intent} that will launch an explicit target activity
492      * specified by sourceActivity's {@link androidx.core.app.NavUtils#PARENT_ACTIVITY} &lt;meta-data&gt;
493      * element in the application's manifest. If the device is running
494      * Jellybean or newer, the android:parentActivityName attribute will be preferred
495      * if it is present.
496      *
497      * @return a new Intent targeting the defined parent activity of sourceActivity
498      */
499     @Override
getSupportParentActivityIntent()500     public @Nullable Intent getSupportParentActivityIntent() {
501         return NavUtils.getParentActivityIntent(this);
502     }
503 
504     /**
505      * Returns true if sourceActivity should recreate the task when navigating 'up'
506      * by using targetIntent.
507      *
508      * <p>If this method returns false the app can trivially call
509      * {@link #supportNavigateUpTo(android.content.Intent)} using the same parameters to correctly perform
510      * up navigation. If this method returns false, the app should synthesize a new task stack
511      * by using {@link androidx.core.app.TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
512      *
513      * @param targetIntent An intent representing the target destination for up navigation
514      * @return true if navigating up should recreate a new task stack, false if the same task
515      *         should be used for the destination
516      */
supportShouldUpRecreateTask(@onNull Intent targetIntent)517     public boolean supportShouldUpRecreateTask(@NonNull Intent targetIntent) {
518         return NavUtils.shouldUpRecreateTask(this, targetIntent);
519     }
520 
521     /**
522      * Navigate from sourceActivity to the activity specified by upIntent, finishing sourceActivity
523      * in the process. upIntent will have the flag {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} set
524      * by this method, along with any others required for proper up navigation as outlined
525      * in the Android Design Guide.
526      *
527      * <p>This method should be used when performing up navigation from within the same task
528      * as the destination. If up navigation should cross tasks in some cases, see
529      * {@link #supportShouldUpRecreateTask(android.content.Intent)}.</p>
530      *
531      * @param upIntent An intent representing the target destination for up navigation
532      */
supportNavigateUpTo(@onNull Intent upIntent)533     public void supportNavigateUpTo(@NonNull Intent upIntent) {
534         NavUtils.navigateUpTo(this, upIntent);
535     }
536 
537     @SuppressWarnings("deprecation")
538     @Override
onContentChanged()539     public void onContentChanged() {
540         // Call onSupportContentChanged() for legacy reasons
541         onSupportContentChanged();
542     }
543 
544     /**
545      * @deprecated Use {@link #onContentChanged()} instead.
546      */
547     @Deprecated
onSupportContentChanged()548     public void onSupportContentChanged() {
549     }
550 
551     @Override
getDrawerToggleDelegate()552     public ActionBarDrawerToggle.@Nullable Delegate getDrawerToggleDelegate() {
553         return getDelegate().getDrawerToggleDelegate();
554     }
555 
556     /**
557      * {@inheritDoc}
558      *
559      * <p>Please note: AppCompat uses its own feature id for the action bar:
560      * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p>
561      */
562     @Override
onMenuOpened(int featureId, Menu menu)563     public boolean onMenuOpened(int featureId, Menu menu) {
564         return super.onMenuOpened(featureId, menu);
565     }
566 
567     /**
568      * {@inheritDoc}
569      *
570      * <p>Please note: AppCompat uses its own feature id for the action bar:
571      * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p>
572      */
573     @Override
onPanelClosed(int featureId, @NonNull Menu menu)574     public void onPanelClosed(int featureId, @NonNull Menu menu) {
575         super.onPanelClosed(featureId, menu);
576     }
577 
578     /**
579      * @return The {@link AppCompatDelegate} being used by this Activity.
580      */
getDelegate()581     public @NonNull AppCompatDelegate getDelegate() {
582         if (mDelegate == null) {
583             mDelegate = AppCompatDelegate.create(this, this);
584         }
585         return mDelegate;
586     }
587 
588     @Override
dispatchKeyEvent(KeyEvent event)589     public boolean dispatchKeyEvent(KeyEvent event) {
590         // Let support action bars open menus in response to the menu key prioritized over
591         // the window handling it
592         final int keyCode = event.getKeyCode();
593         final ActionBar actionBar = getSupportActionBar();
594         if (keyCode == KeyEvent.KEYCODE_MENU
595                 && actionBar != null && actionBar.onMenuKeyEvent(event)) {
596             return true;
597         }
598         return super.dispatchKeyEvent(event);
599     }
600 
601     @Override
getResources()602     public Resources getResources() {
603         if (mResources == null && VectorEnabledTintResources.shouldBeUsed()) {
604             mResources = new VectorEnabledTintResources(this, super.getResources());
605         }
606         return mResources == null ? super.getResources() : mResources;
607     }
608 
609     /**
610      * KeyEvents with non-default modifiers are not dispatched to menu's performShortcut in API 25
611      * or lower. Here, we check if the keypress corresponds to a menuitem's shortcut combination
612      * and perform the corresponding action.
613      */
performMenuItemShortcut(KeyEvent event)614     private boolean performMenuItemShortcut(KeyEvent event) {
615         if (!(Build.VERSION.SDK_INT >= 26) && !event.isCtrlPressed()
616                 && !KeyEvent.metaStateHasNoModifiers(event.getMetaState())
617                 && event.getRepeatCount() == 0
618                 && !KeyEvent.isModifierKey(event.getKeyCode())) {
619             final Window currentWindow = getWindow();
620             if (currentWindow != null && currentWindow.getDecorView() != null) {
621                 final View decorView = currentWindow.getDecorView();
622                 if (decorView.dispatchKeyShortcutEvent(event)) {
623                     return true;
624                 }
625             }
626         }
627         return false;
628     }
629 
630     @Override
onKeyDown(int keyCode, KeyEvent event)631     public boolean onKeyDown(int keyCode, KeyEvent event) {
632         if (performMenuItemShortcut(event)) {
633             return true;
634         }
635         return super.onKeyDown(keyCode, event);
636     }
637 
638     @Override
openOptionsMenu()639     public void openOptionsMenu() {
640         ActionBar actionBar = getSupportActionBar();
641         if (getWindow().hasFeature(Window.FEATURE_OPTIONS_PANEL)
642                 && (actionBar == null || !actionBar.openOptionsMenu())) {
643             super.openOptionsMenu();
644         }
645     }
646 
647     @Override
closeOptionsMenu()648     public void closeOptionsMenu() {
649         ActionBar actionBar = getSupportActionBar();
650         if (getWindow().hasFeature(Window.FEATURE_OPTIONS_PANEL)
651                 && (actionBar == null || !actionBar.closeOptionsMenu())) {
652             super.closeOptionsMenu();
653         }
654     }
655 
656     /**
657      * Called when the night mode has changed. See {@link AppCompatDelegate#applyDayNight()} for
658      * more information.
659      *
660      * @param mode the night mode which has been applied
661      */
onNightModeChanged(@ightMode int mode)662     protected void onNightModeChanged(@NightMode int mode) {
663     }
664 
665     /**
666      * Called when the locales have been changed. See {@link AppCompatDelegate#applyAppLocales()}
667      * for more information.
668      *
669      * @param locales the localeListCompat which has been applied
670      */
onLocalesChanged(@onNull LocaleListCompat locales)671     protected void onLocalesChanged(@NonNull LocaleListCompat locales) {
672     }
673 }
674