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