-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Defining The ActionBar
The ActionBar is a consistent navigation element that is standard throughout modern Android applications. The ActionBar can consist of:
- An application icon
- An application or activity-specific title
- Primary action buttons for an activity
- Consistent navigation (including tabbed UI)
Important to note that prior to 3.0, there was no ActionBar although there is a compatibility library that comes bundled that provides limited ActionBar functionality to older versions. There is now a support library called ActionBarCompat which provides much better compatibility for older versions (including support for tabbed interfaces).
Every application unless otherwise specified has an ActionBar by default. The ActionBar by default just has the application icon and an activity title.
The ActionBar icon and title displayed at the top of the screen is governed by the AndroidManifest.xml
file within the activity
nodes. In the example below, the activity "FirstActivity" will have an ActionBar with the string value of the resource identified by @string/activity_name
. If the value of that resource is "Foo," the string displayed in the ActionBar for this activity will be "Foo." Note that the application
node can supply a android:label
that acts as the default for activities and components with no other specified label.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.codepath.example.simpleapp.FirstActivity"
android:label="@string/activity_name" >
</activity>
</application>
Change the android:label
or android:icon
to modify the ActionBar icon or title for a given activity or for the application as a whole. In any Java activity, you can also call getActionBar()
to retrieve a reference to the ActionBar and modify or access any properties of the ActionBar at runtime:
ActionBar actionBar = getSupportActionBar(); // or getActionBar();
String title = actionBar.getTitle().toString();
actionBar.hide();
You can also change many other properties of the ActionBar not covered here. See the Extended ActionBar Guide for more details.
When you want to add primary actions to the ActionBar, you add the items to the activity context menu and if properly specified, they will automatically appear at the top.
An activity populates the action bar in its onCreateOptionsMenu()
method:
public class MainActivity extends ActionBarActivity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Entries in the action bar are typically called actions. Use this method to inflate a menu resource that defines all the action items within a res/menu
xml file, for example:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/miCompose"
android:icon="@drawable/ic_compose"
app:showAsAction="ifRoom"
android:title="Compose">
</item>
<item
android:id="@+id/miProfile"
android:icon="@drawable/ic_profile"
app:showAsAction="ifRoom|withText"
android:title="Profile">
</item>
</menu>
Notice that to request that an item appear directly in the action bar as an action button, include showAsAction="ifRoom"
in the <item>
tag. If there's not enough room for the item in the action bar, it will appear in the action overflow. If withText
is specified as well (as in the second item), the text will be displayed with the icon.
Note: The above code refers to the @drawable/ic_compose
resource which would have to exist for this to compile. To generate ActionBar icons, be sure to use the Asset Studio in Android Studio. To create a new Android icon set, right click on a res\drawable
folder and invoke New->Image Asset.
There are two ways to handle the click for an ActionBar item. The first approach is you can use the android:onClick
handler in the menu XML, similar to handling button clicks:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/item1"
android:icon="@drawable/ic_compose"
android:onClick="onComposeAction"
app:showAsAction="ifRoom"
android:title="Compose">
</item>
</menu>
and then define the method onComposeAction
in the parent activity before attempting to run the application or an exception will be thrown for the missing method:
public class MainActivity extends ActionBarActivity {
public void onComposeAction(MenuItem mi) {
// handle click here
}
}
The second approach is to use the onOptionsItemSelected()
method. Using the MenuItem passed to this method, you can identify the action by calling getItemId(). This returns the unique ID provided by the item tag's id attribute so you can perform the appropriate action:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.miCompose:
composeMessage();
return true;
case R.id.miProfile:
showProfileView();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
and then you can handle all the action buttons in this single method.
ToolBar was introduced in Android Lollipop, API 21 release and is a complete replacement to ActionBar. It's a ViewGroup so you can place it anywhere in your layout. ToolBar also provides greater control to customize its appearance for the same reason.
ToolBar works well with apps targeted to API 21 and above. However, Android has updated the AppCompat support libraries so the ToolBar can be used on lower Android OS devices as well. In AppCompat, ToolBar is implemented in the android.support.v7.widget.Toolbar
class.
There are two ways to use Toolbar:
- Use a Toolbar as an Action Bar when you want to use the existing Action Bar facilities (such as menu inflation and selection, ActionBarDrawerToggle, and so on) but want to have more control over its appearance.
- Use a standalone Toolbar when you want to use the pattern in your app for situations that an Action Bar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.
To use Toolbar as an ActionBar, first disable the decor-provided ActionBar. The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar
(or its light variant) in styles.xml
file.
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
</resources>
Secondly, add the AppCompat-v7 support library to your application build.gradle
file:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "com.android.support:appcompat-v7:21.0.+"
}
Now you need to add Toolbar to your Activity layout:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
</android.support.v7.widget.Toolbar>
As Toolbar is just a ViewGroup
, it can be styled and positioned like any other view. Then in your Activity or Fragment, set the Toolbar to act as your ActionBar by using the setSupportActionBar(Toolbar)
method:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
public class MyActivity extends ActionBarActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Set a ToolBar to replace the ActionBar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
From this point on, all menu items are displayed in your Toolbar, populated via the standard options menu callbacks.
- http://developer.android.com/guide/topics/ui/actionbar.html
- http://developer.android.com/design/patterns/actionbar.html
- http://developer.android.com/reference/android/app/ActionBar.html
- http://www.vogella.com/articles/AndroidActionBar/article.html
- http://jgilfelt.github.io/android-actionbarstylegenerator
- http://android-developers.blogspot.com/2014/10/appcompat-v21-material-design-for-pre.html
Created by CodePath with much help from the community. Contributed content licensed under cc-wiki with attribution required. You are free to remix and reuse, as long as you attribute and use a similar license.
Finding these guides helpful?
We need help from the broader community to improve these guides, add new topics and keep the topics up-to-date. See our contribution guidelines here and our topic issues list for great ways to help out.
Check these same guides through our standalone viewer for a better browsing experience and an improved search. Follow us on twitter @codepath for access to more useful Android development resources.