I have a fragment with that needs to build its own action bar :
public class CalendarFragment extends Fragment {
public CalendarFragment() {
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().supportInvalidateOptionsMenu();
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.calendar_menu1, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText("Calendar Fragment");
return textView;
}
}
the problem is it doesnt create a new menu with items from calendar_menu1 but just adds the items from it to the old menu, as if invalidateOptionsMenu doesnt work (i tried getActivity().invalidateOptionsMenu() too)
You must call in onCreate():
setHasOptionsMenu(true);
It is normal, looking into the javadoc of the MenuInflater, "The items and submenus will be added to this Menu":
public void inflate (int menuRes, Menu menu)
Inflate a menu hierarchy from the specified XML resource. Throws InflateException if there is an error.
Parameters
menuRes Resource ID for an XML layout resource to load (e.g., R.menu.main_activity)
menu The Menu to inflate into. The items and submenus will be added to this Menu.
Did you try to call menu.clear()
before to inflate your fragment menu?
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.calendar_menu1, menu);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With