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