Trying to hide/disable entire menu (overflow) in f

2019-04-02 04:11发布

问题:

I have been unsuccessful in trying to hide or disable the overflow menu in one fragment.

I have tried setting setHasOptionsMenu(false) with no success, and then I tried setHasOptionsMenu(true) and tried inflating with an empty menu like below.

Both attempts do not work for me.

How do I hide or disable the options/overflow menu in one fragment only??

Thanks in advance!

Fragment

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

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Inflate the menu; this adds items to the action bar if it is present.
    inflater.inflate(R.menu.empty, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

回答1:

Figured out how to do it. Just need to set the menu items I don't want visible. In my case, I set all of them not visible and that removed the overflow menu entirely.

Also don't forget you have to setHasOptionsMenu(true) in your onCreate so it knows to call onCreateOptionsMenu

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (menu != null) {
        menu.findItem(R.id.menu_settings).setVisible(false);
        menu.findItem(R.id.menu_leave_feedback).setVisible(false);
        menu.findItem(R.id.menu_shop).setVisible(false);
    }
}


回答2:

 setHasOptionsMenu(true)

in OnCreate() and

 @Override
        public void onPrepareOptionsMenu(Menu menu) {
            // if nav drawer is opened, hide the action items       
                menu.findItem(R.id.xxx).setVisible(false);
                menu.findItem(R.id.yyy).setVisible(false);              
        }


回答3:

I know this answer is very late but I like to share it.
In Fragment onCreate method:

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

        setHasOptionsMenu(true);

    }


And in Fragment onCreateOptionsMenu() method:

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        menu.clear();
    }