我正在创建一个女巫的测验应用程序:当使用时选择一个答案用户将导航到下一个屏幕。
我想要的是从这里开始:
我想阻止用户返回上一个屏幕,
如果用户尝试通过点击后退按钮返回上一个屏幕,则会出现退出确认消息。
如果用户选择" OK"应用程序应关闭,如果用户选择"取消/(继续测验)"该应用应该从当前屏幕继续。
答案 0 :(得分:2)
您需要以这种方式覆盖活动onBackPressed
@Override
public void onBackPressed() {
AlertDialog dlg = new AlertDialog.Builder(YourActivity.this).create();
dlg.setCancelable(false);
dlg.setTitle("CLOSE");
dlg.setMessage("Are you sure?");
dlg.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dlg.setButton(DialogInterface.BUTTON_POSITIVE, "CLOSE APP", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
YourActivity.super.onBackPressed();
}
});
dlg.show();
}
答案 1 :(得分:0)
您可以覆盖活动中的onBackPressed()
功能。
@Override
public void onBackPressed() {
// code for displaying confirm message here
}
此答案包含用于创建确认对话框的示例代码:https://stackoverflow.com/a/6413736/379245