Android Create a simple menu programmatically

后端 未结 5 928
遥遥无期
遥遥无期 2021-02-01 12:36

I\'m trying to create a simple menu with one button that will call a method to clear the array. I don\'t want to use xml because all I need is one button.

Something like

5条回答
  •  遥遥无期
    2021-02-01 12:53

    Something like this might work:

    public boolean onCreateOptionsMenu(Menu menu) {
      MenuItem item = menu.add ("Clear Array");
      item.setOnMenuItemClickListener (new OnMenuItemClickListener(){
        @Override
        public boolean onMenuItemClick (MenuItem item){
          clearArray();
          return true;
        }
      });
      return true;
    }
    

    Menu gives us a handy method, add(), which allows you to add a MenuItem. So we make one. Then we assign an OnMenuItemClickListener to the MenuItem and override its onMenuItemClick() to do what we want it to do.

提交回复
热议问题