2

I am developing an app, where I am using Swipable Tabs - implemented using FragmentActivity and respective Fragment for each Tab.

Now I have checkboxes in each Fragment (Tab). I need to enable few Menu items in the Action Bar (like Send/ Share/ Delete) of the app when the checkbox is checked and disable these menus when the checkbox is unchecked.

How can we achieve this? Any pointers will be appreciated.

-- Ramky

Ramky
  • 23
  • 1
  • 1
  • 4
  • you can check the second answer of this question: http://stackoverflow.com/questions/7133141/android-changing-option-menu-items-programmatically – eric wang Jan 22 '15 at 01:04

2 Answers2

6

Changing menu items at runtime

After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle.

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)

Ref documentation

@Override
 public boolean onPrepareOptionsMenu (Menu menu) {
     if (condition_true)
         menu.getItem(item_index).setEnabled(false);
     return true;
 }
spidergears
  • 194
  • 11
  • +1 for the mention of fragments! The only difference is that the overridden method returns `void` instead of the `boolean`. – Neph Mar 24 '20 at 14:36
2
public Menu toggleMenu;
boolean isflag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.your_menu,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    toggleMenu = menu;
    toggleItem();
    return super.onPrepareOptionsMenu(menu);
}
public void toggleItem(){
    MenuItem item1= toggleMenu.findItem(R.id.item1);
    MenuItem item2= toggleMenu.findItem(R.id.item2);
    if(isflag)
    {
        item1.setVisible(false);
        item2.setVisible(true);
    }
    else
    {
        item1.setVisible(true);
        item2.setVisible(false);
    }
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()){

        case R.id.item1:
            isflag = true;
            toggleItem();
            break;

        case R.id.item2:
            isflag = false;
            toggleItem();
            break;
    }
    return super.onOptionsItemSelected(item);
}
Mostafa Azadi
  • 2,893
  • 2
  • 12
  • 19