How to add a menu in a fragment?
To add a menu for each fragment, you should go through many steps:
1) First of all, add setHasOptionsMenu(true) in the fragment's onCreateView() like below:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
....
}
2) Override fragment's onCreateOptionsMenu() method as below:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.menu_above_details_fragment, menu);
return;
}
3) Override the activity's onOptionsItemSelected() method like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
Intent i;
switch (item.getItemId()) {
case R.id.action_param:
i = new Intent(this, Settings.class);
startActivity(i);
return true;
case R.id.action_history:
i = new Intent(this, HistoryMenu.class);
startActivity(i);
return true;
}
return onOptionsItemSelected(item);
}
4) Don't override the fragment's onOptionsItemSelected(), nor activity's onCreateOptionsMenu().