Activity在要实现Menu,需要重写下面的几个方法:
创建Menu:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
响应Menu事件:
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId())
{
case R.id.menu_save:
Toast.makeText(MainActivity.this,"Save is Selected",Toast.LENGTH_SHORT).show();
break;
case R.id.menu_search:
Toast.makeText(MainActivity.this,"Search is Selected",Toast.LENGTH_SHORT).show();
break;
case R.id.menu_share:
Toast.makeText(MainActivity.this,"Share is Selected",Toast.LENGTH_SHORT).show();
break;
case R.id.menu_del:
Toast.makeText(MainActivity.this,"Del is Selected",Toast.LENGTH_SHORT).show();
break;
}
return super.onMenuItemSelected(featureId, item);
}
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_save"
android:title="Save"/>
<item
android:id="@+id/menu_search"
android:title="Search"/>
<item
android:id="@+id/menu_share"
android:title="Share"/>
<item
android:id="@+id/menu_del"
android:title="Delete"/>
</menu>
android:showAsAction="always"
显示到标题栏, 可以设置图标,也可以将一个layout显示到actionba.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_save"
android:icon="@android:drawable/ic_menu_save"
android:showAsAction="ifRoom"
android:title="Save"/>
<item
android:id="@+id/menu_search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="ifRoom"
android:title="Search"/>
<item
android:id="@+id/menu_share"
android:actionLayout="@layout/activity_main"
android:icon="@android:drawable/ic_menu_share"
android:showAsAction="ifRoom|withText"
android:title="Share"/>
<item
android:id="@+id/menu_del"
android:icon="@android:drawable/ic_menu_delete"
android:showAsAction="ifRoom|withText"
android:title="Delete"/>
</menu>
参考链接 :