ActionBarActivity.java revision 469286122bcbbecbdd0bef74fb50f9d8920e77b9
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 onTitleChanged(CharSequence title, int color) {
169        super.onTitleChanged(title, color);
170        getDelegate().onTitleChanged(title);
171    }
172
173    /**
174     * Enable extended support library window features.
175     * <p>
176     * This is a convenience for calling
177     * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
178     * </p>
179     *
180     * @param featureId The desired feature as defined in
181     * {@link android.view.Window} or {@link WindowCompat}.
182     * @return Returns true if the requested feature is supported and now enabled.
183     *
184     * @see android.app.Activity#requestWindowFeature
185     * @see android.view.Window#requestFeature
186     */
187    public boolean supportRequestWindowFeature(int featureId) {
188        return getDelegate().supportRequestWindowFeature(featureId);
189    }
190
191    @Override
192    public void supportInvalidateOptionsMenu() {
193        getDelegate().supportInvalidateOptionsMenu();
194    }
195
196    /**
197     * @hide
198     */
199    public void invalidateOptionsMenu() {
200        getDelegate().supportInvalidateOptionsMenu();
201    }
202
203    /**
204     * Notifies the Activity that a support action mode has been started.
205     * Activity subclasses overriding this method should call the superclass implementation.
206     *
207     * @param mode The new action mode.
208     */
209    public void onSupportActionModeStarted(ActionMode mode) {
210    }
211
212    /**
213     * Notifies the activity that a support action mode has finished.
214     * Activity subclasses overriding this method should call the superclass implementation.
215     *
216     * @param mode The action mode that just finished.
217     */
218    public void onSupportActionModeFinished(ActionMode mode) {
219    }
220
221    public ActionMode startSupportActionMode(ActionMode.Callback callback) {
222        return getDelegate().startSupportActionMode(callback);
223    }
224
225    @Override
226    public boolean onCreatePanelMenu(int featureId, Menu menu) {
227        return getDelegate().onCreatePanelMenu(featureId, menu);
228    }
229
230    @Override
231    public boolean onPreparePanel(int featureId, View view, Menu menu) {
232        return getDelegate().onPreparePanel(featureId, view, menu);
233    }
234
235    @Override
236    public void onPanelClosed(int featureId, Menu menu) {
237        getDelegate().onPanelClosed(featureId, menu);
238    }
239
240    @Override
241    public boolean onMenuOpened(int featureId, Menu menu) {
242        return getDelegate().onMenuOpened(featureId, menu);
243    }
244
245    /**
246     * @hide
247     */
248    @Override
249    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
250        return getDelegate().onPrepareOptionsPanel(view, menu);
251    }
252
253    void superSetContentView(int resId) {
254        super.setContentView(resId);
255    }
256
257    void superSetContentView(View v) {
258        super.setContentView(v);
259    }
260
261    void superSetContentView(View v, ViewGroup.LayoutParams lp) {
262        super.setContentView(v, lp);
263    }
264
265    void superAddContentView(View v, ViewGroup.LayoutParams lp) {
266        super.addContentView(v, lp);
267    }
268
269    boolean superOnCreatePanelMenu(int featureId, android.view.Menu frameworkMenu) {
270        return super.onCreatePanelMenu(featureId, frameworkMenu);
271    }
272
273    boolean superOnPreparePanel(int featureId, View view, android.view.Menu menu) {
274        return super.onPreparePanel(featureId, view, menu);
275    }
276
277    boolean superOnPrepareOptionsPanel(View view, Menu menu) {
278        return super.onPrepareOptionsPanel(view, menu);
279    }
280
281    void superOnPanelClosed(int featureId, Menu menu) {
282        super.onPanelClosed(featureId, menu);
283    }
284
285    boolean superOnMenuOpened(int featureId, Menu menu) {
286        return super.onMenuOpened(featureId, menu);
287    }
288
289    @Override
290    public void onBackPressed() {
291        if (!getDelegate().onBackPressed()) {
292            super.onBackPressed();
293        }
294    }
295
296    /**
297     * Support library version of {@link Activity#setProgressBarVisibility(boolean)}
298     * <p>
299     * Sets the visibility of the progress bar in the title.
300     * <p>
301     * In order for the progress bar to be shown, the feature must be requested
302     * via {@link #supportRequestWindowFeature(int)}.
303     *
304     * @param visible Whether to show the progress bars in the title.
305     */
306    public void setSupportProgressBarVisibility(boolean visible) {
307        getDelegate().setSupportProgressBarVisibility(visible);
308    }
309
310    /**
311     * Support library version of {@link Activity#setProgressBarIndeterminateVisibility(boolean)}
312     * <p>
313     * Sets the visibility of the indeterminate progress bar in the title.
314     * <p>
315     * In order for the progress bar to be shown, the feature must be requested
316     * via {@link #supportRequestWindowFeature(int)}.
317     *
318     * @param visible Whether to show the progress bars in the title.
319     */
320    public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
321        getDelegate().setSupportProgressBarIndeterminateVisibility(visible);
322    }
323
324    /**
325     * Support library version of {@link Activity#setProgressBarIndeterminate(boolean)}
326     * <p>
327     * Sets whether the horizontal progress bar in the title should be indeterminate (the
328     * circular is always indeterminate).
329     * <p>
330     * In order for the progress bar to be shown, the feature must be requested
331     * via {@link #supportRequestWindowFeature(int)}.
332     *
333     * @param indeterminate Whether the horizontal progress bar should be indeterminate.
334     */
335    public void setSupportProgressBarIndeterminate(boolean indeterminate) {
336        getDelegate().setSupportProgressBarIndeterminate(indeterminate);
337    }
338
339    /**
340     * Support library version of {@link Activity#setProgress(int)}.
341     * <p>
342     * Sets the progress for the progress bars in the title.
343     * <p>
344     * In order for the progress bar to be shown, the feature must be requested
345     * via {@link #supportRequestWindowFeature(int)}.
346     *
347     * @param progress The progress for the progress bar. Valid ranges are from
348     *            0 to 10000 (both inclusive). If 10000 is given, the progress
349     *            bar will be completely filled and will fade out.
350     */
351    public void setSupportProgress(int progress) {
352        getDelegate().setSupportProgress(progress);
353    }
354
355    /**
356     * Support version of {@link #onCreateNavigateUpTaskStack(android.app.TaskStackBuilder)}.
357     * This method will be called on all platform versions.
358     *
359     * Define the synthetic task stack that will be generated during Up navigation from
360     * a different task.
361     *
362     * <p>The default implementation of this method adds the parent chain of this activity
363     * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
364     * may choose to override this method to construct the desired task stack in a different
365     * way.</p>
366     *
367     * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
368     * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
369     * returned by {@link #getParentActivityIntent()}.</p>
370     *
371     * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
372     * by the manifest should override
373     * {@link #onPrepareSupportNavigateUpTaskStack(TaskStackBuilder)}.</p>
374     *
375     * @param builder An empty TaskStackBuilder - the application should add intents representing
376     *                the desired task stack
377     */
378    public void onCreateSupportNavigateUpTaskStack(TaskStackBuilder builder) {
379        builder.addParentStack(this);
380    }
381
382    /**
383     * Support version of {@link #onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder)}.
384     * This method will be called on all platform versions.
385     *
386     * Prepare the synthetic task stack that will be generated during Up navigation
387     * from a different task.
388     *
389     * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
390     * Intents as generated by {@link #onCreateSupportNavigateUpTaskStack(TaskStackBuilder)}.
391     * If any extra data should be added to these intents before launching the new task,
392     * the application should override this method and add that data here.</p>
393     *
394     * @param builder A TaskStackBuilder that has been populated with Intents by
395     *                onCreateNavigateUpTaskStack.
396     */
397    public void onPrepareSupportNavigateUpTaskStack(TaskStackBuilder builder) {
398    }
399
400    /**
401     * This method is called whenever the user chooses to navigate Up within your application's
402     * activity hierarchy from the action bar.
403     *
404     * <p>If a parent was specified in the manifest for this activity or an activity-alias to it,
405     * default Up navigation will be handled automatically. See
406     * {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity
407     * along the parent chain requires extra Intent arguments, the Activity subclass
408     * should override the method {@link #onPrepareSupportNavigateUpTaskStack(TaskStackBuilder)}
409     * to supply those arguments.</p>
410     *
411     * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and
412     * Back Stack</a> from the developer guide and
413     * <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide
414     * for more information about navigating within your app.</p>
415     *
416     * <p>See the {@link TaskStackBuilder} class and the Activity methods
417     * {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(Intent)}, and
418     * {@link #supportNavigateUpTo(Intent)} for help implementing custom Up navigation.</p>
419     *
420     * @return true if Up navigation completed successfully and this Activity was finished,
421     *         false otherwise.
422     */
423    public boolean onSupportNavigateUp() {
424        Intent upIntent = getSupportParentActivityIntent();
425
426        if (upIntent != null) {
427            if (supportShouldUpRecreateTask(upIntent)) {
428                TaskStackBuilder b = TaskStackBuilder.create(this);
429                onCreateSupportNavigateUpTaskStack(b);
430                onPrepareSupportNavigateUpTaskStack(b);
431                b.startActivities();
432
433                try {
434                    ActivityCompat.finishAffinity(this);
435                } catch (IllegalStateException e) {
436                    // This can only happen on 4.1+, when we don't have a parent or a result set.
437                    // In that case we should just finish().
438                    finish();
439                }
440            } else {
441                // This activity is part of the application's task, so simply
442                // navigate up to the hierarchical parent activity.
443                supportNavigateUpTo(upIntent);
444            }
445            return true;
446        }
447        return false;
448    }
449
450    /**
451     * Obtain an {@link Intent} that will launch an explicit target activity
452     * specified by sourceActivity's {@link NavUtils#PARENT_ACTIVITY} &lt;meta-data&gt;
453     * element in the application's manifest. If the device is running
454     * Jellybean or newer, the android:parentActivityName attribute will be preferred
455     * if it is present.
456     *
457     * @return a new Intent targeting the defined parent activity of sourceActivity
458     */
459    public Intent getSupportParentActivityIntent() {
460        return NavUtils.getParentActivityIntent(this);
461    }
462
463    /**
464     * Returns true if sourceActivity should recreate the task when navigating 'up'
465     * by using targetIntent.
466     *
467     * <p>If this method returns false the app can trivially call
468     * {@link #supportNavigateUpTo(Intent)} using the same parameters to correctly perform
469     * up navigation. If this method returns false, the app should synthesize a new task stack
470     * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
471     *
472     * @param targetIntent An intent representing the target destination for up navigation
473     * @return true if navigating up should recreate a new task stack, false if the same task
474     *         should be used for the destination
475     */
476    public boolean supportShouldUpRecreateTask(Intent targetIntent) {
477        return NavUtils.shouldUpRecreateTask(this, targetIntent);
478    }
479
480    /**
481     * Navigate from sourceActivity to the activity specified by upIntent, finishing sourceActivity
482     * in the process. upIntent will have the flag {@link Intent#FLAG_ACTIVITY_CLEAR_TOP} set
483     * by this method, along with any others required for proper up navigation as outlined
484     * in the Android Design Guide.
485     *
486     * <p>This method should be used when performing up navigation from within the same task
487     * as the destination. If up navigation should cross tasks in some cases, see
488     * {@link #supportShouldUpRecreateTask(Intent)}.</p>
489     *
490     * @param upIntent An intent representing the target destination for up navigation
491     */
492    public void supportNavigateUpTo(Intent upIntent) {
493        NavUtils.navigateUpTo(this, upIntent);
494    }
495
496    @Override
497    public final ActionBarDrawerToggle.Delegate getDrawerToggleDelegate() {
498        return getDelegate().getDrawerToggleDelegate();
499    }
500
501    @Nullable
502    @Override
503    /**
504     * Temporary method until ActionBarDrawerToggle transition from v4 to v7 is complete.
505     */
506    public android.support.v7.app.ActionBarDrawerToggle.Delegate getV7DrawerToggleDelegate() {
507        return getDelegate().getV7DrawerToggleDelegate();
508    }
509
510    @Override
511    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
512        return getDelegate().onKeyShortcut(keyCode, event);
513    }
514
515    @Override
516    public boolean onKeyDown(int keyCode, KeyEvent event) {
517        // First let the Activity try and handle it (for back, etc)
518        if (super.onKeyDown(keyCode, event)) {
519            return true;
520        }
521        return getDelegate().onKeyDown(keyCode, event);
522    }
523
524    /**
525     * Use {@link #onSupportContentChanged()} instead.
526     */
527    public final void onContentChanged() {
528        getDelegate().onContentChanged();
529    }
530
531    /**
532     * This hook is called whenever the content view of the screen changes.
533     * @see android.app.Activity#onContentChanged()
534     */
535    public void onSupportContentChanged() {
536    }
537
538    @Override
539    public View onCreateView(String name, @NonNull Context context, @NonNull AttributeSet attrs) {
540        // Allow super (FragmentActivity) to try and create a view first
541        final View result = super.onCreateView(name, context, attrs);
542        if (result != null) {
543            return result;
544        }
545        // If we reach here super didn't create a View, so let our delegate attempt it
546        return getDelegate().createView(name, attrs);
547    }
548
549    private ActionBarActivityDelegate getDelegate() {
550        if (mDelegate == null) {
551            mDelegate = ActionBarActivityDelegate.createDelegate(this);
552        }
553        return mDelegate;
554    }
555}
556