In addition to displaying the application icon and Activity title on the left side of the ActionBar, you can also display additional items on the ActionBar. These added projects are called "action items ". These projects are shortcuts for some features in your application. For example, if you are developing an RSS reader, action items may be "refresh", "delete", or "add ".
The following example shows how to add a project to the ActionBar.
1. Use the code in MyActionBarActivity. java from the project in the previous section.
[Java]
Public class MyActionBarActivity extends Activity {
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// ActionBar actionBar = getActionBar ();
// ActionBar. hide ();
// ActionBar. show (); // --- show it again ---
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
Super. onCreateOptionsMenu (menu );
CreateMenu (menu );
Return true;
}
@ Override
Public boolean onOptionsItemSelected (MenuItem item)
{
Return MenuChoice (item );
}
Private void CreateMenu (Menu menu)
{
MenuItem mnu1 = menu. add (0, 0, 0, "Item 1 ");
{
Mnu1.setIcon (R. drawable. ic_launcher );
Mnu1.setShowAsAction (
MenuItem. SHOW_AS_ACTION_IF_ROOM );
}
MenuItem mnu2 = menu. add (0, 1, 1, "Item 2 ");
{
Mnu2.setIcon (R. drawable. ic_launcher );
Mnu2.setShowAsAction (
MenuItem. SHOW_AS_ACTION_IF_ROOM );
}
MenuItem mnu3 = menu. add (0, 2, 2, "Item 3 ");
{
Mnu3.setIcon (R. drawable. ic_launcher );
Mnu3.setShowAsAction (
MenuItem. SHOW_AS_ACTION_IF_ROOM );
}
MenuItem mnu4 = menu. add (0, 3, 3, "Item 4 ");
{
Mnu4.setShowAsAction (
MenuItem. SHOW_AS_ACTION_IF_ROOM |
MenuItem. SHOW_AS_ACTION_WITH_TEXT );
}
MenuItem mnu5 = menu. add (0, 4, 4, "Item 5 ");
{
Mnu5.setShowAsAction (
MenuItem. SHOW_AS_ACTION_IF_ROOM );
}
}
Private boolean MenuChoice (MenuItem item)
{
Switch (item. getItemId ()){
Case 0:
Toast. makeText (this, "You clicked on Item 1 ",
Toast. LENGTH_LONG). show ();
Return true;
Case 1:
Toast. makeText (this, "You clicked on Item 2 ",
Toast. LENGTH_LONG). show ();
Return true;
Case 2:
Toast. makeText (this, "You clicked on Item 3 ",
Toast. LENGTH_LONG). show ();
Return true;
Case 3:
Toast. makeText (this, "You clicked on Item 4 ",
Toast. LENGTH_LONG). show ();
Return true;
Case 4:
Toast. makeText (this, "You clicked on Item 5 ",
Toast. LENGTH_LONG). show ();
Return true;
}
Return false;
}
}
2. Perform F11 debugging. Observe the icon on the right of the ActionBar.
If you press the menu button, the remaining menu options are displayed. "Floating" menu.
3. Click the menu item and a prompt will pop up.
4. Press Ctrl + F11 to change the display direction of the simulator. Four options are displayed: three buttons and a text box.