-1

我想在我的应用程序中添加菜单,但它不起作用。菜单项显示正确,但是当我选择其中一项时,什么也没有发生。我还想在 item2 上显示一个警报对话框。请帮助我。我是安卓新手。

提前致谢

我试过这个

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);
}
4

1 回答 1

-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类成员

于 2013-04-27T20:42:44.757 回答