问题
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 only after button is click.
回答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.
private boolean isTickVisible = false;
Then you need to override OnPrepareOptions menu like below and set the visibility of the tick menu.
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem someMenuItem = 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.
回答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);
}
}
来源:https://stackoverflow.com/questions/37807538/android-inflate-menu-add-items-to-action-bar-only-on-click-of-a-button