invalidateOptionsMenu doesn't work in fragment

前端 未结 3 477
梦毁少年i
梦毁少年i 2021-02-04 00:44

I want to show or hide item in actionbar according to either their is text in the edit text or not

so I did the following

            public class Noun         


        
3条回答
  •  灰色年华
    2021-02-04 01:41

    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);
    
    
    }
    

提交回复
热议问题