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?
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;
}
It seems you have to change visibility in an onPrepareOptionsMenu().
See this answer: Set visibility in Menu programatically android
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