invalidateOptionsMenu doesn't work in fragment

For updating the onCreateOptionsMenu inside the fragment you need to call the setHasOptionsMenu(true); inside the onCreate method of the fragment. Otherwise you won't be able to update it when you call getActivity().invalidateOptionsMenu();

sample:

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

EDIT:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if(seachEditText.getText().toString().length() > 0)
        {
            menu.findItem(R.id.action_search).setVisible(true);
        }
        else
        {
            menu.findItem(R.id.action_search).setVisible(false);
        }
    super.onCreateOptionsMenu(menu, inflater);


}

Try this:

@Override
public boolean onPrepareOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onPrepareOptionsMenu(menu, inflater);
    if (seachEditText.getText().toString().length() > 0) {
        menu.findItem(R.id.action_search).setVisible(true);
    } else {
        menu.findItem(R.id.action_search).setVisible(false);
    }
}

Solution 1

This is work in fragment

 getActivity().invalidateOptionsMenu();

Solution 2

Try this if above code is not working

invalidateOptionsMenu(getActivity());

Import this library

import static androidx.core.app.ActivityCompat.invalidateOptionsMenu;