菜单设计一
// 创建菜单
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "关于");
menu.add(0, 1, 1, "退出");
return super.onCreateOptionsMenu(menu);
}
//菜单响应
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case 0:
Toast.makeText(MainActivity.this, "欢迎", Toast.LENGTH_LONG).show();
case 1:
this.finish();
}
return true;
}
菜单设计二
1.添加menu.xml 在目录Resmenu下
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- group1 -->
<group android:id="@+id/group1">
<item android:id="@+id/menu1"
android:title="menu1"/>
<item android:id="@+id/menu2"
android:title="menu2"/>
</group>
<!-- group 2 -->
<group android:id="@+id/group2">
<item android:id="@+id/menu3"
android:title="menu3"/>
<item android:id="@+id/menu4"
android:title="menu4"/>
</group>
</menu>
2.创建菜单加载menu.xml
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
3.菜单响应
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu1:
// do sth
break;
case R.id.menu2:
// do sth
break;
case R.id.menu3:
// do sth
break;
case R.id.menu4:
// do sth
break;
}
return true;
}