简体   繁体   中英

How do I hide the OptionMenu in a toolbar from a fragment?

I inflate the option menu in the HomeActivity . But i need the option menu to show in some fragments , and hide in others.

I tried with setHasOptionsMenu(false); line in onCreate() fragment method.

This is the optionmenu button declaration in HomeActivity

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //initialize button
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.option_menu, menu);
    return true;
}

//action when i press it
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // action with ID action_refresh was selected
        case R.id.toolbar_acquista:
            Toast.makeText(this, "Acquisto", Toast.LENGTH_SHORT)
                    .show();
            break;
    }

    return true;
}

I'm trying to have this in a fragment the option menu clickable and visible, in others unclickable and invisible.

first Clear Menu like

@Override 
public void onPrepareOptionsMenu(Menu menu) {
    menu.clear();
}

and then TRUE as setHasOptionsMenu(true); in onCreate() of fragment method

don't inflate menu in home activity instead inflate menu inside the fragments

like this

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

this way menuitems inflated in the fragments only visible when the fragment is visible

First of all Override Create Method in Fragment and write setHasOptionsMenu(true)

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

Then after override OnPrepareOptionMenu method in Fragment and Write code which i place inside it. I hide my Search Menu only. Similarly You can hide all menu item or selective item as per your choice.

   @Override
public void onPrepareOptionsMenu(Menu menu) {
    MenuItem item=menu.findItem(R.id.menu_search);
    if(item!=null)
        item.setVisible(false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM