Home > Mobile >  How to hide MenuItem in the toolbar in certain situations?
How to hide MenuItem in the toolbar in certain situations?

Time:04-21

I have a form screen that is also an information screen, but in different states. When the user enters to create I want to hide the MenuItem that assigns to delete. How to do this without breaking the app? I'm trying to call it like this:

val menu = findViewById<MenuItem>(R.id.deleteBarra)

CodePudding user response:

Here's the docs about it, but you basically want to do your menu setup in onPrepareOptionsMenu instead of onCreateOptionsMenu. onPrepareOptionsMenu gets called every time the menu needs to be displayed (instead of once, during setup).

So you can set a boolean or whatever to say whether the item should be shown, and call invalidateOptionsMenu() to redisplay it. In prepareOptionsMenu() you have access to the menu itself, so you can check that boolean and set the visibility on the appropriate item

CodePudding user response:

Under what condition you want it to be hidden, you can add it under that condition.

  menu.visibility = View.INVISIBLE

or

   menu.visibility = View.GONE
  • Related