Android: Inflate menu (add items to action bar) only on click of a button

烈酒焚心 提交于 2019-12-13 09:15:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!