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.
Hide button by default in menu xml By default the share button will be hidden, as set by android:visible="false" .
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.
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.
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;
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With