除了在Action Bar的左侧显示应用程序图标和活动名称以外,还可以在Action Bar上显示其他项,这些项叫做动作项。动作项是应用程序中经常执行的一些操作的快捷方式。
package com.example.androidtest; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MyActionBarActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_action_bar); } @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 menu1 = menu.add(0, 0, 0, "Item 1"); { menu1.setIcon(R.drawable.ic_launcher); //SHOW_AS_ACTION_IF_ROOM: 如果Action Bar上有空间, //则将该菜单项显示为一个动作项 menu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } MenuItem menu2 = menu.add(0, 1, 1, "Item 2"); { menu2.setIcon(R.drawable.ic_launcher); menu2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } MenuItem menu3 = menu.add(0, 2, 2, "Item 3"); { menu3.setIcon(R.drawable.ic_launcher); menu3.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } MenuItem menu4 = menu.add(0, 3, 3, "Item 4"); { menu4.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } MenuItem menu5 = menu.add(0, 4, 4, "Item 5"); { menu5.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; } }
运行效果