Create a new xml file; res/menu/menu.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_add"
android:icon="@drawable/ic_action_add"
android:orderInCategory="100"
android:title="@string/action_search"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:orderInCategory="100"
android:title="@string/action_search"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/action_settings"
android:icon="@drawable/ic_action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="ifRoom"/>
</menu>
To add the menu in the activity you need to override following two methods;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Do some action
return true;
case R.id.action_settings: {
//Do some action
return true;
}
case R.id.action_add: {
//Do some action
return true;
}
}
return super.onOptionsItemSelected(item);
}
Fragments will follow the same menu is an in the parent activity. In case you want to modify menu for a fragment, you have to setHasOptionsMenu(true) in onCreate method;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Now you can manipulate a menu. Let’s say you want to hide a specific action;
@Override
public void onCreateOptionsMenu(Menu menu , MenuInflater inflater){
mMenu.findItem(R.id.action_add).setVisible(false);
super.onCreateOptionsMenu(menu,inflater);
}
You can also hide the whole menu for a fragment;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
}
You can create a fragment specific menu and inflate the menu for that fragment. Create a new menu i.e. res/menu/menu_fragment.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_settings"
android:icon="@drawable/ic_action_settings"
android:orderInCategory="2"
android:title="@string/action_settings"
app:showAsAction="ifRoom"/>
</menu>
and now you can either extend this menu with the activity menu or use it as the only menu.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//map.clear(); //Clear the previous menu from the activity.
inflater.inflate(R.menu.menu_fragment, menu);
}
Now you can override the method onOptionsItemSelected to handle item selection.