Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onPrepareOptionsMenu not getting called in Fragments

Tags:

java

android

    @Override
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
        Log.d("Does", "get called");
        inflater.inflate(R.menu.menuItem, menu);
        super.onCreateOptionsMenu(menu,inflater);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        getActivity().invalidateOptionsMenu();
        MenuItem filter = menu.findItem(R.id.section);

        filter.setVisible(false);

    }

I am trying to load my menu in fragments and its getting loaed, but the onPrepareOptionsMenu is not getting called at all, where i need to hide some menu-items.

Update:

    @Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setHasOptionsMenu(true);
}

I am calling setHasOptionsMenu(true) inside my onCreate() method.

like image 529
Kevin Avatar asked Mar 27 '13 10:03

Kevin


3 Answers

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

http://developer.android.com/guide/topics/ui/menus.html

To change particular item use: menu.findItem(R.id.your_item_id)

like image 156
trickster77777 Avatar answered Nov 16 '22 18:11

trickster77777


You need to do two things. Step 1: In Fragment OnCreateView add setHasOptionsMenu(true);

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    setHasOptionsMenu(true);
    return inflater.inflate(R.layout.fragment_user_settings, container, false);
}

Step 2: you need to add getActivity().invalidateOptionsMenu(); in your fragment in OnViewCreated. Or in mainActivity when you change the Fragment.

like image 15
SanRam Avatar answered Nov 16 '22 18:11

SanRam


Probably too late, but I had same problem and the solution was really simple. Just call getActivity().invalidateOptionsMenu() from your fragment. This will call onPrepareOptionsMenu and here you can control the visibility of your items like this: menu.findItem(R.id.youritem).setVisible(true/false); Hope that helps!

like image 9
Carlos Borau Avatar answered Nov 16 '22 20:11

Carlos Borau