onCreateOptionsMenu inside Fragments
Call
setSupportActionBar(toolbar)
inside
onViewCreated(...)
of Fragment
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((MainActivity)getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
}
try this,
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_sample, menu);
super.onCreateOptionsMenu(menu,inflater);
}
Finally, in onCreateView
method, add this line to make the options appear in your Toolbar
setHasOptionsMenu(true);
Your already have the autogenerated file res/menu/menu.xml defining action_settings.
In your MainActivity.java have the following methods:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
// do stuff, like showing settings fragment
return true;
}
return super.onOptionsItemSelected(item); // important line
}
In the onCreateView()
method of your Fragment call:
setHasOptionsMenu(true);
and also add these 2 methods:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_1:
// do stuff
return true;
case R.id.action_2:
// do more stuff
return true;
}
return false;
}
Finally, add the new file res/menu/fragment_menu.xml defining action_1 and action_2.
This way when your app displays the Fragment, its menu will contain 3 entries:
- action_1 from res/menu/fragment_menu.xml
- action_2 from res/menu/fragment_menu.xml
- action_settings from res/menu/menu.xml
I tried the @Alexander Farber and @Sino Raj answers. Both answers are nice, but I couldn't use the onCreateOptionsMenu inside my fragment, until I discover what was missing:
Add setSupportActionBar(toolbar) in my Activity, like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
I hope this answer can be helpful for someone with the same problem.