我想在我的应用程序中添加菜单,但它不起作用。菜单的项目显示正确但当我选择其中一个时,没有任何反应。 另外我想在item2上显示一个警告对话框。 请帮助我。我是android的新手。
提前致谢
我试过这个
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater in=getMenuInflater();
in.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.item1:
this.finish();
break;
case R.id.item2:
AlertDialog.Builder bb=new AlertDialog.Builder(this);
bb.setMessage("Are you sure to exit?").setCancelable(false);
bb.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
bb.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alrt=bb.create();
//alrt.setTitle("Are you sure to exit?");
alrt.show();
break;
}
return super.onOptionsItemSelected(item);
}
答案 0 :(得分:-1)
尝试这种方法:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, OK_MENU_ITEM, 0, "Ok");
menu.add(0, SAVE_MENU_ITEM, 0, "Save");
menu.add(0, BACK_MENU_ITEM, 0, "Back");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OK_MENU_ITEM:
//showMsg("Ok");
break;
case SAVE_MENU_ITEM:
//showMsg("Save");
break;
case BACK_MENU_ITEM:
//showMsg("Back");
break;
}
return super.onOptionsItemSelected(item);
}
将OK_MENU_ITEM BACK_MENU_ITEM SAVE_MENU_ITEM定义为final int
班级成员