由于近3周内没有其他答案,我将自己回答我的问题:
而不是重写
public boolean onCreateOptionsMenu(Menu menu)
一个人必须超越
public boolean onPrepareOptionsMenu(Menu menu)
下面是一个简单的例子,如何做到这一点:
活动中有以下代码:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
showMenu();
return true;
}
private void showMenu() {
EditMenu menu = new EditMenu(this, "Pacman Menu");
menu.show();
}
然后,clsas editmenu以如下方式查找示例:
public class EditMenu {
private final String QUIT = "Quit";
private final String RESTART = "New Game";
private final String SOUND = "Switch Sound";
private final String PAUSE = "Un/pause";
private final CharSequence[] items = new CharSequence[] {QUIT, RESTART, SOUND, PAUSE};
private Context context;
private String title;
private AlertDialog alert;
private MenuListener listener = new MenuListener();
public EditMenu(Context context, String title) {
this.context = context;
this.title = title;
}
public void show() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.drawable.splashscreen);
builder.setTitle(title);
builder.setItems(items, listener);
alert = builder.create();
alert.show();
}
private class MenuListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(QUIT)) {
((PacmanGame) context).quitGame();
} else if (items[item].equals(RESTART)) {
((PacmanGame) context).restart();
} else if (items[item].equals(SOUND)) {
Sound.setSoundOn(! Sound.isSoundOn());
} else if (items[item].equals(PAUSE)) {
((PacmanGame) context).getGameBoard().setPausing(!(((PacmanGame) context).getGameBoard().isPaused()));
}
}
}
}