Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set visibility in Menu programmatically android

Tags:

android

So, that´s what I wanna know. How can I set the visibility of the menu programatically in Android?? This is how I have my menu:

public boolean onCreateOptionsMenu(Menu menu){     MenuInflater inflater = getMenuInflater();     inflater.inflate(R.menu.menu, menu);     return true; }  public boolean onOptionsItemSelected (MenuItem item){     switch (item.getItemId()){         case R.id.menuregistrar:             break;         case R.id.menusalir:             break;     }     return true; } 

But this code is not on the onCreate, so I don´t know how to set one item visible or invisible programmatically (in my case, I want the "menuregistrar" to be invisible once I have registered my application and forever.

like image 401
zapotec Avatar asked Jan 27 '12 07:01

zapotec


People also ask

How can I hide menu items in Android?

Hide button by default in menu xml By default the share button will be hidden, as set by android:visible="false" .

What is onCreateOptionsMenu in Android?

Find the onCreateOptionsMenu(Menu menu) method which needs to override in Activity class. This creates menu and returns Boolean value. inflate inflates a menu hierarchy from XML resource. public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater(). inflate(R.

How do we hide the menu on the toolbar in one fragment?

When you click the show button to open a fragment, you can see the fragment menu items ordered before activity menu items. This is because of the menu item's android:orderInCategory attribute value. When you click the hide button to hide the fragment. The fragment menu items disappear from the action bar also.


2 Answers

Put this method in your Activity

public boolean onPrepareOptionsMenu(Menu menu) {     MenuItem register = menu.findItem(R.id.menuregistrar);           if(userRegistered)      {                    register.setVisible(false);     }     else     {         register.setVisible(true);     }     return true; } 

in shorter version you could write:

MenuItem register = menu.findItem(R.id.menuregistrar);       register.setVisible(!userRegistered);  //userRegistered is boolean, pointing if the user has registered or not. return true; 
like image 66
Adil Soomro Avatar answered Sep 18 '22 15:09

Adil Soomro


I would simplify Adil's solution even further with the following:

public boolean onPrepareOptionsMenu(Menu menu) {     MenuItem registrar = menu.findItem(R.id.menuregistrar);           registrar.setVisible(!isRegistered);     return true; } 
like image 45
jakeneff Avatar answered Sep 19 '22 15:09

jakeneff