Android: Inflate Menu (add Items To Action Bar) Only On Click Of A Button
I am trying to inflate a menu only onclick of a button in android. How do i achieve it without creating it automatically by calling onCreateOptionsMenu. I want the menu to appear o
Solution 1:
First add this icon in you action R.menu... file and set the visibility as false.
Have a boolean instance variable in our java file.
privatebooleanisTickVisible=false;
Then you need to override OnPrepareOptions menu like below and set the visibility of the tick menu.
@OverridepublicvoidonPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItemsomeMenuItem= menu.findItem(R.id.tick_menu_item);
someMenuItem.setVisible(isTickVisible);
}
Finally onClick event of your button do the following :
isTickVisible = true;
invalidateOptionsMenu(); //this will redraw your menu.
Solution 2:
I fixed this issue by setting the visibility.Inflate the layout and make it visible only on clicking the button.Add a flag inside onClickListener eg:Hide=true;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
for (int i = 0; i < menu.size(); i++)
if(Hide){
menu.getItem(i).setVisible(true);
}
}
Post a Comment for "Android: Inflate Menu (add Items To Action Bar) Only On Click Of A Button"