【发布时间】:2012-01-10 10:12:20
【问题描述】:
我正在尝试制作一个对话框按钮,当我在主要活动上时会弹出一个对话框按钮,并询问用户是否确定要关闭程序。我不确定在 //Action for the Yes 按钮中添加什么...有没有更好的方法来做到这一点?
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Exit Game?");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
【问题讨论】:
-
按下 ok 按钮时调用 finish() 可以解决问题
-
我建议重写
onBackPressed()函数而不是处理特定的键事件。