在res /菜单中定义菜单
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/first_item_id" android:orderInCategory="100" android:title="@string/first_item_string" android:icon="@drawable/first_item_icon" app:showAsAction="ifRoom"/> <item android:id="@+id/second_item_id" android:orderInCategory="110" android:title="@string/second_item_string" android:icon="@drawable/second_item_icon" app:showAsAction="ifRoom"/> </menu>
有关配置的更多选项,请参考:菜单资源
内部Activity:
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { ///覆盖定义菜单资源 inflater.inflate(R.menu.menu_resource_id, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public void onPrepareOptionsMenu(Menu menu) { //覆盖准备项目(设置可见性,更改文本,更改图标...) super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { //覆盖它以处理项目 int menuItemId = item.getItemId(); switch (menuItemId) { case: R.id.first_item_id return true; //如果已处理,则返回true } return super.onOptionsItemSelected(item); }
要在显示视图时调用上述方法,请调用 getActivity().invalidateOptionsMenu();
内部Fragment需要另外一个呼叫:
@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); super.onCreateView(inflater, container, savedInstanceState); }