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