Setting an ActionBar button visibility to GONE - android

I have a toolbar with some actionbar buttons. I would like the camera icon button NOT to appear if the
Build.VERSION.SDK_INT < 21.
in the following menu file I define the actionbar buttons:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="#+id/addons"
android:icon="#drawable/ic_add_box_black_24dp"
android:title="camera"
app:showAsAction="always"/>
<item
android:id="#+id/hellosearch"
android:icon="#drawable/ic_search_black_24dp"
android:title="camera"
app:showAsAction="always"/>
//inside the MainActivity I override the method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addons:
//we are requesting to purchase something:
Log.d("billing009","trying to start a purchase!! user has accesss(subs): "+user_has_autorenew_subs+
" didFind :: " + didFindTotalAccess);
showPurchaseDialog(styled_title);
//inHouseMethod_StartPurchase();
break;
case R.id.hellosearch:
mDrawer.openDrawer(GravityCompat.START);
return true;
HOWEVER, this method gets called when the user clicks on one of the actionbar buttons.
How can I use the toolbar object created inside onCreate: to get a hold of the Camera icon(ActionBar button), so I can set its visibility to GONE if the Build.VERSION.SDK_INT < 21 ?
//inside onCreate
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

You can do that inside onCreateOptionsMenu like
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.your_menu_xml, menu);
if(Build.VERSION.SDK_INT < 21) {
MenuItem item = menu.findItem(R.id.idOfYourMenuItem);
item.setVisible(false);
}
return true;
}

Put this method in your Activity
public boolean onPrepareOptionsMenu(Menu menu)
{
MenuItem camera = menu.findItem(R.id.addons);
if(Build.VERSION.SDK_INT < 21)
{
camera.setVisible(true);
}
else
{
camera.setVisible(false);
}
return true;
}
onPrepareOptionsMenu Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
onCreateOptionsMenu() is called once.
onPrepareOptionsMenu() is called every time the menu opens.
From the onCreateOptionsMenu() documentation:
This is only called once, the first time the options menu is
displayed. To update the menu every time it is displayed, see
onPrepareOptionsMenu(Menu).

Related

Remove Toolbar items on runtime

I have a Toolbar within my app which I would like to modify it contents dynamically, during the app execution (in other words, on run-time).
For example, the app is capable of taking and previewing photos; once that photos are previewed, the user is able to select some photos and perform a sending action to a server. I want also to make the user able to delete photos once that some of them are selected and for doing that I would like that the "delete" item on the action bar (identifiable via the trash icon) will be visible only when one or more photos are selected.
Is this possible to do?
If yes, how?
In other words and, more generically, I want to control items (visibility) in the toolbar, setting the code as they will be "visible" only when some conditions are "true" (in the example above, when photos are selected or, in a different example, when user is logged) and invisible when they are "false" (when user isn't logged).
For now I just need to "remove" (or make invisible) items in the Toolbar, but it will be useful also to know if is possible to add items in the toolbar on run-time.
I'm adding some code which can help to understand the problem.
app_bar.xml file in "/res/layout", which graphically defines the Toolbar
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:elevation="4dp"
android:theme="#style/ToolbarTheme" />
menu_resources.xml file, which defines the Toolbar items
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- "User favourite function", should appear as action button if possible -->
<item
android:id="#+id/action_app_icon"
android:icon="#mipmap/ic_launcher"
android:title="#string/action_bar_app_icon"
app:showAsAction="always" />
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_delete"
android:icon="#drawable/trash"
android:title="#string/action_bar_delete"
app:showAsAction="always"/>
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_settings"
android:icon="#drawable/settings"
android:title="#string/action_bar_settings"
app:showAsAction="never"/>
<!-- About, should always be in the overflow -->
<item
android:id="#+id/about"
android:icon="#android:drawable/ic_dialog_info"
app:showAsAction="never"
android:title="#string/action_bar_about"/>
Part of the activity in which the toolbar is
public class myClass extends AppCompatActivity implements View.OnClickListener {
// Instantiating a toolbar
private Toolbar toolbar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_class);
// Adding toolbar to the activity
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
// The method that creates an options menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_resource, menu);
// This make the delete item invisible
menu.findItem(R.id.action_delete).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// Perform the settings action
return true;
case R.id.about:
// Perform the about
return true;
case R.id.action_delete:
deletePhotos();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static void manageSelection(Boolean state, int position){
if (photoArray.getNumberSelected() == 0) {
// disable the trash icon and its functionality;
} else {
// enable the trash icon with its functionality;
}
}
// This method allows to deleteItems images to the array
public void deletePhotos() {
//code for deleting photos
}
}
Thanks for your time.
Try this code in your activity please:
public class ActivityClass extends AppCompatActivity {
MenuItem menuItem; // Make global toolbar's menuItem
.
.
.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
menuItem = menu.findItem(R.id.toolbar_action_button) // Your toolbar´s button ID and save it in your global menuItem
return super.onCreateOptionsMenu(menu);
}
public void showMenuItem(){
menuItem.setVisible(true); // Call this method in runtime when you need show it
}
public void hideMenuItem(){
menuItem.setVisible(false); // Call this method in runtime when you need hide it
}
[EDIT]
Thanks to Alessandro Iudicone´s comment we have an alternative way to get the toolbar´s menu too without the global MenuItem but only global Toolbar instance:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
return super.onCreateOptionsMenu(menu);
}
public void showMenuItem(){
toolbar.getMenu().findItem(R.id.toolbar_actio‌​n_button).setVisible‌​(true);
}
public void hideMenuItem(){
toolbar.getMenu().findItem(R.id.toolbar_actio‌​n_button).setVisible‌​(false);
}
Hope it helps :)
For hiding the icon:
toolbar.findViewById(R.id.menu_item_id).setVisibility(View.INVISIBLE);
For adding a view to the toolbar:
TextView textView = new TextView(MainActivity.this);
textView.setText("Hello World");
toolbar.addView(textView);
This only works for views on the toolbar itself, not for the overflow menu. You'll probably have to use code found in this stack overflow answer if you want to mess with the overflow menu: Android Toolbar overflow menu view id

Changing menu items on a toolbar menu made from a xml layout

So I have this toolbar in my app, and I want to display different menu items depending on whether the user is logged in or not. When the user logs in or out I want to update my layout which for now is the toolbar menu to represent the change. For some reason though, my menu items are not removed at all, all of them are visible at all times, regardless of the login state.
My menu items:
<menu
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_add"
android:icon="#drawable/ic_action_add"
android:title="#string/action_add"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/action_login"
android:icon="#drawable/ic_action_logged_out"
android:title="#string/action_log_in"
app:showAsAction="always"/>
<item
android:id="#+id/action_logout"
android:icon="#drawable/ic_action_logged_in"
android:title="#string/action_log_out"
app:showAsAction="always"/>
</menu>
The first menu item is only supposed to be visible to a user that is logged in. Also I guess it's self explanatory but I only want one of the log in/out buttons to be visible depending on the login state.
My Java code:
protected void initializeToolbar(){
myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
menu = myToolbar.getMenu();
resetToolbarMenu();
myToolbar.setOnMenuItemClickListener(this);
}
private void resetToolbarMenu(){
menu.clear();
getMenuInflater().inflate(R.menu.menu, menu);
if(loginPrefs.getBoolean("login", false)) { //loginPrefs is reference to a SharedPreference object
menu.removeItem(1);
} else {
menu.removeItem(2);
menu.removeItem(0);
}
}
Reason I got two methods is that I only want to set up the toolbar and listener once, but I want to be able to change the menu every time the user logs in/out without reloading the page.
After a successful login the resetToolbarMenu() method will be called again.
I suppose the menu.remove(0) does not update the UI, but I could not find another way to reach my menu object without first inflating it and then getting it from the toolbar, and I assume the inflation is what decides what items are visible. Basically, I could not find a way to remove any menu items before inflating or updating the UI in another way than inflating.
Solution:
I changed my java code into something like this:
protected void initializeToolbar(){
myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu); // Don't know if this is necessary or if returning true is prefered.
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(loginPrefs.getBoolean("login", false)) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(false);
menu.getItem(2).setVisible(true);
} else {
menu.getItem(0).setVisible(false);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(false);
}
return true;
}
I also had to call invalidateOptionsMenu() on logout/login to update the toolbar/menu. However onPrepareOptionsMenu() is also automatically called whenever you open the menu for items that aren't shown on the toolbar itself.
PS: OnCreateOptionsMenu and OnPrepareOptionsMenu will not be used unless you remember to setSupportActionBar(myToolbar) as I forgot.
You can create options menu by overriding onCreateOptionsMenu. You can create 2 xml and inflate either one of them depending on your logic. To force a redraw of the menu, you can call invalidateOptionsMenu.
For example
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if (login) {
inflater.inflate(R.menu.login_menu, menu);
} else {
inflater.inflate(R.menu.logout_menu, menu);
}
return true;
}
And outside change the flag and force redraw
login = false; // or true
invalidateOptionsMenu();
You have to override onPrepareOptionsMenu in the activity to change the items in the menu.
From the documentation:
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

MenuItem.setIcon() method doesn't work

I've tried already all possible solutions. Here's my code:
private Menu mMenu;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_article_detail_menu, menu);
mMenu = menu;
}
void changeStar(boolean added) {
if (mMenu != null) {
MenuItem item = mMenu.findItem(R.id.favourites_item);
if (added) {
Log.d(LOG_TAG, "Set full icon");
item.setIcon(getResources().getDrawable(R.drawable.star_full));
} else {
Log.d(LOG_TAG, "Set empty icon");
item.setIcon(getResources().getDrawable(R.drawable.star_empty));
}
}
}
Here is my menu xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="ssidit.pp.ua.payspacereader.ArticleDetailActivity">
<item
android:id="#+id/refresh_item"
android:title="#string/refresh"
app:showAsAction="never"></item>
<item
android:id="#+id/favourites_item"
android:icon="#drawable/star_empty"
android:title="#string/add_to_favourite"
app:showAsAction="ifRoom"></item>
<item
android:id="#+id/share_item"
android:icon="#drawable/ic_share"
android:title="#string/share"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
app:showAsAction="ifRoom"></item>
</menu>
invalidateMenu() method doesn't help. When I call setIcon method, nothing changes on my android device.
Here is my code:
private boolean isFavourite;
private void setValues(Cursor cursor) {
Log.d(LOG_TAG, "Setting values");
setData(titleTextView, CursorUtility.getTitle(cursor));
setData(dateTextView, CursorUtility.getDateText(cursor));
setData(timeTextView, CursorUtility.getTimeText(cursor));
isFavourite = CursorUtility.isFavourite(cursor);
getActivity().invalidateOptionsMenu();
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
Log.d(LOG_TAG, "OnPrepareOptionsMenu");
MenuItem item = menu.findItem(R.id.favourites_item);
if (isFavourite) {
Log.d(LOG_TAG, "Set full icon");
item.setIcon(R.drawable.star_full);
} else {
Log.d(LOG_TAG, "Set empty icon");
item.setIcon(R.drawable.star_empty);
}
}
As you can see, everything is logged. So there can't be mistake if some method doesn't call. Also I checked item by getting title of it. It is right item. Just some kind of black magic.
Try using invalidateOptionsMenu and move your changeStar logic to onPrepareOptionsMenu. From Android documentation:
public boolean onPrepareOptionsMenu (Menu menu)
Added in API level 1
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.
Firstly: make a global variable of menu
Secondly: wherever in activity you want to change the icon just get that menu item by global variable menu using getItem() method instead of findItem.
Thirdly: set the icon to your menuItem returned by getItem() as follow menuItem.setIcon(res)

Changing the actionbar menu state depending on fragment

I am trying to show/hide items in my action bar depending on which fragment is visible.
In my MainActivity I have the following
/* Called whenever invalidateOptionsMenu() is called */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(this.myFragment.isVisible()){
menu.findItem(R.id.action_read).setVisible(true);
}else{
menu.findItem(R.id.action_read).setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
This works great however, when the device is rotated there is a issue. After the rotation is complete onPrepareOptionsMenu is called again however this time this.myFragment.isVisible() returns false...and hence the menu item is hidden when clearly the fragment is visible (as far as whats shown on the screen).
Based on the Fragments API Guide, we can add items to the action bar on a per-Fragment basis with the following steps:
Create a res/menu/fooFragmentMenu.xml that contains menu items as you normally would for the standard menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/newAction"
android:orderInCategory="1"
android:showAsAction="always"
android:title="#string/newActionTitle"
android:icon="#drawable/newActionIcon"/>
</menu>
Toward the top of FooFragment's onCreate method, indicate that it has its own menu items to add.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
...
}
Override onCreateOptionsMenu, where you'll inflate the fragment's menu and attach it to your standard menu.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fooFragmentMenu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Override onOptionItemSelected in your fragment, which only gets called when this same method of the host Activity/FragmentActivity sees that it doesn't have a case for the selection.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.newAction:
...
break;
}
return super.onOptionsItemSelected(item);
}
Try using Fragment's setRetainInstance(true); when your fragment is attached to the Activity. That way your fragment will retain it's current values and call the lifecycle when device rotated.
Edit: This is a quick and dirty fix, see es0329's answer below for a better solution.
Try adding this attribute to your activity tag in your android manifest:
android:configChanges="orientation|screenSize"

Android: How to enable/disable option menu item on button click?

I can easily do it when I am using onCreateOptionsMenu or onOptionsItemSelected methods.
But I have a button somewhere in screen, and on clicking that button, it should enable/disable context menu items.
Anyway, the documentation covers all the things.
Changing menu items at runtime
Once the activity is created, the
onCreateOptionsMenu() method is called
only once, as described above. The
system keeps and re-uses the Menu you
define in this method until your
activity is destroyed. If you want to
change the Options Menu any time after
it's first created, you must override
the onPrepareOptionsMenu() method.
This passes you the Menu object as it
currently exists. This is useful if
you'd like to remove, add, disable, or
enable menu items depending on the
current state of your application.
E.g.
#Override
public boolean onPrepareOptionsMenu (Menu menu) {
if (isFinalized) {
menu.getItem(1).setEnabled(false);
// You can also use something like:
// menu.findItem(R.id.example_foobar).setEnabled(false);
}
return true;
}
On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().
On all android versions, easiest way: use this to SHOW a menu action icon as disabled AND make it FUNCTION as disabled as well:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.menu_my_item);
if (myItemShouldBeEnabled) {
item.setEnabled(true);
item.getIcon().setAlpha(255);
} else {
// disabled
item.setEnabled(false);
item.getIcon().setAlpha(130);
}
}
You could save the item as a variable when creating the option menu and then change its properties at will.
private MenuItem securedConnection;
private MenuItem insecuredConnection;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.connect_menu, menu);
securedConnection = menu.getItem(0);
insecuredConnection = menu.getItem(1);
return true;
}
public void foo(){
securedConnection.setEnabled(true);
}
How to update the current menu in order to enable or disable the items when an AsyncTask is done.
In my use case I needed to disable my menu while my AsyncTask was loading data, then after loading all the data, I needed to enable all the menu again in order to let the user use it.
This prevented the app to let users click on menu items while data was loading.
First, I declare a state variable , if the variable is 0 the menu is shown, if that variable is 1 the menu is hidden.
private mMenuState = 1; //I initialize it on 1 since I need all elements to be hidden when my activity starts loading.
Then in my onCreateOptionsMenu() I check for this variable , if it's 1 I disable all my items, if not, I just show them all
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_galeria_pictos, menu);
if(mMenuState==1){
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setVisible(false);
}
}else{
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setVisible(true);
}
}
return super.onCreateOptionsMenu(menu);
}
Now, when my Activity starts, onCreateOptionsMenu() will be called just once, and all my items will be gone because I set up the state for them at the start.
Then I create an AsyncTask Where I set that state variable to 0 in my onPostExecute()
This step is very important!
When you call invalidateOptionsMenu(); it will relaunch onCreateOptionsMenu();
So, after setting up my state to 0, I just redraw all the menu but this time with my variable on 0 , that said, all the menu will be shown after all the asynchronous process is done, and then my user can use the menu.
public class LoadMyGroups extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mMenuState = 1; //you can set here the state of the menu too if you dont want to initialize it at global declaration.
}
#Override
protected Void doInBackground(Void... voids) {
//Background work
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mMenuState=0; //We change the state and relaunch onCreateOptionsMenu
invalidateOptionsMenu(); //Relaunch onCreateOptionsMenu
}
}
Results
simplify #Vikas version
#Override
public boolean onPrepareOptionsMenu (Menu menu) {
menu.findItem(R.id.example_foobar).setEnabled(isFinalized);
return true;
}
A more modern answer for an old question:
MainActivity.kt
private var myMenuIconEnabled by Delegates.observable(true) { _, old, new ->
if (new != old) invalidateOptionsMenu()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.my_button).setOnClickListener { myMenuIconEnabled = false }
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main_activity, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menu.findItem(R.id.action_my_action).isEnabled = myMenuIconEnabled
return super.onPrepareOptionsMenu(menu)
}
menu_main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_my_action"
android:icon="#drawable/ic_my_icon_24dp"
app:iconTint="#drawable/menu_item_icon_selector"
android:title="My title"
app:showAsAction="always" />
</menu>
menu_item_icon_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?enabledMenuIconColor" android:state_enabled="true" />
<item android:color="?disabledMenuIconColor" />
attrs.xml
<resources>
<attr name="enabledMenuIconColor" format="reference|color"/>
<attr name="disabledMenuIconColor" format="reference|color"/>
</resources>
styles.xml or themes.xml
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="disabledMenuIconColor">#color/white_30_alpha</item>
<item name="enabledMenuIconColor">#android:color/white</item>
What I did was save a reference to the Menu at onCreateOptionsMenu. This is similar to nir's answer except instead of saving each individual item, I saved the entire menu.
Declare a Menu Menu toolbarMenu;.
Then in onCreateOptionsMenusave the menu to your variable
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu, menu);
toolbarMenu = menu;
return true;
}
Now you can access your menu and all of its items anytime you want.
toolbarMenu.getItem(0).setEnabled(false);
the best solution
when you are perform on navigation drawer
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.setGroupVisible(0,false);
return true;
}
If visible menu
menu.findItem(R.id.id_name).setVisible(true);
If hide menu
menu.findItem(R.id.id_name).setVisible(false);
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_id:
//Your Code....
item.setEnabled(false);
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.home, menu);
return false;
}
Generally can change the properties of your views in runtime:
(Button) item = (Button) findViewById(R.id.idBut);
and then...
item.setVisibility(false)
but
if you want to modify de visibility of the options from the ContextMenu, on press your button, you can activate a flag, and then in onCreateContextMenu you can do something like this:
#Override
public void onCreateContextMenu(ContextMenu menu,
View v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(R.string.context_title);
if (flagIsOn()) {
addMenuItem(menu, "Option available", true);
} else {
Toast.makeText(this, "Option not available", 500).show();
}
}
I hope this helps

Categories

Resources