1. If you don't already have an Android project, create an Android Project.
2. Ensure your minSdkVersion is 11, or greater. Action Bar only runs on API Level 11 and later.
Also, use the Action Bar instead of the Options Menu. The Action Bar replaces the traditional application
title bar.
While in the AndroidManifest.xml file, make sure you do NOT have the below line in your application tag. Otherwise, your Action Bar will not display.
3. Create an Options Menu with the below items in the XML file. Skip adding icons, for now, and remove that line from the items.
Name: menu_add
Title: Add
Name: menu_saveSave: Save
Name: menu_search Title: Search Name: menu_share
Title: Share
Name: menu_delete
Title: Delete
Name: menu_preferences Title: Preferences
4. Compile and test. You should see the Action Bar and items in it. The items will not do anything yet though.
5. Let's make them do something! Open MainActivity.java and add the below to the imports section.
import android.widget.Toast;
import android.view.MenuItem;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
Toast.makeText(MainActivity.this, "Add is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_save:
Toast.makeText(MainActivity.this, "Save is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_search:
Toast.makeText(MainActivity.this, "Search is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_share:
Toast.makeText(MainActivity.this, "Share is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_delete:
Toast.makeText(MainActivity.this, "Delete is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_preferences:
Toast.makeText(MainActivity.this, "Preferences is Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
6. Compile and run!
Other Action Bar Articles
- Add an Icon to an Item in the Action Bar
- Set the Title and Subtitle on the Action Bar
Resources:
http://developer.android.com/guide/topics/ui/actionbar.html
http://developer.android.com/guide/topics/resources/menu-resource.html
http://www.darshancomputing.com/android/1.5-drawables.html