Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change visibility for MenuItem dynamically?

Tags:

android

I'm developing some Android application and I have ActionBar with 2 tabs. I need to show 2 icons on ActionBar when user select the second tab. I have the following code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    mOptionsMenu=menu;
    menu.getItem(0).setVisible(false);
    menu.getItem(1).setVisible(false);
    return true;
} 

    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        mViewPager.setCurrentItem(tab.getPosition());
        if (tab.getPosition()==1) {
        mOptionsMenu.getItem(0).setVisible(true);
        mOptionsMenu.getItem(1).setVisible(true);
}
    }

But this code doesn't work. Please, tell me, how can I done my needs?

like image 224
malcoauri Avatar asked Dec 07 '25 04:12

malcoauri


2 Answers

You need to set the menu visible in the onPrepareOptionsMenu(). You could change your code as follow:

private boolean menuShow = false;

public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
    mViewPager.setCurrentItem(tab.getPosition()); 
    if (tab.getPosition()==1) { 
      menuShow = true;
    } 
}


public boolean onPrepareOptionsMenu(Menu menu) {
  if(menuShow){
    mOptionsMenu.getItem(0).setVisible(true);    
    mOptionsMenu.getItem(1).setVisible(true);
  }
  return true;
}
like image 75
Luis Avatar answered Dec 08 '25 16:12

Luis


It seems you have to change visibility in an onPrepareOptionsMenu().

See this answer: Set visibility in Menu programatically android

like image 41
Plasma Avatar answered Dec 08 '25 18:12

Plasma