代码设置menu形式:
public class MainActivity extends Activity{ private final int MENU_ID_SETTING = 1; private final int MENU_ID_EXIT = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //重写onCreateOptionsMenu创建菜单 @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0,MENU_ID_SETTING,0,"设置"); menu.add(0,MENU_ID_EXIT,0,"退出"); return super.onCreateOptionsMenu(menu); } //重写onOptionsItemSelected设置菜单事件 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ID_SETTING: Toast.makeText(this, "设置", Toast.LENGTH_LONG).show(); break; case MENU_ID_EXIT: Toast.makeText(this, "退出", Toast.LENGTH_LONG).show(); break; default: break; } return super.onOptionsItemSelected(item); }}
清单配置形式:
public class MainActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { //通过xml配置菜单 MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.setmenu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.item1: Toast.makeText(this, "设置", Toast.LENGTH_LONG); break; default: break; } return super.onMenuItemSelected(featureId, item); }}