Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalidateOptionsMenu doesnt get called from fragment

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)

like image 908
user924941 Avatar asked Aug 09 '12 09:08

user924941


2 Answers

You must call in onCreate():

setHasOptionsMenu(true);
like image 187
Nik Avatar answered Nov 15 '22 15:11

Nik


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);
}
like image 38
L. G. Avatar answered Nov 15 '22 14:11

L. G.