无法让Android应用退出

时间:2017-02-17 13:50:11

标签: java android alertdialog android-alertdialog

我努力让我的Android应用程序通过alertdialog退出。

点击“是”'再次播放工作正常,因为它重新启动应用程序,你会再次去。

不幸的是,当我点击“没有”时,它只是删除了对话框警告框,我无法找出原因。

非常感谢任何帮助。

由于

@Override
       public void onClick(View v) {
           AlertDialog.Builder alert = new    AlertDialog.Builder(Task1Activity.this);
           alert.setMessage("You have guessed incorrectly three times. " +
               "The answer was " + ranNum + ". " + "Would you like to play again?")
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
    public void onClick(DialogInterface dialog, int which) {

    Intent i = new Intent(Task1Activity.this, Task1Activity.class);
    startActivity(i);

    }
});

alert
.setCancelable(false)
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Task1Activity.this.finish();
};
)
    .setTitle("Unlucky!")
    .create();

3 个答案:

答案 0 :(得分:1)

您正在创建活动Intent i = new Intent(Task1Activity.this, Task1Activity.class);,该活动在堆栈上添加了活动。

试试这段代码:

 final AlertDialog.Builder alertDialog = new AlertDialog.Builder(
        Task1Activity.this);
alertDialog.setTitle("Unlucky!");
alertDialog.setCancelable(false)
alertDialog.setMessage("You have guessed incorrectly three times. " +
           "The answer was " + ranNum + ". " + "Would you like to play again?");
alertDialog.setPositiveButton("YES",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)        {
                 Intent i = new Intent(Task1Activity.this, Task1Activity.class);
                 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                startActivity(i);
            }
        });
alertDialog.setNegativeButton("NO",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog.dismiss();   
                //getActivity().finish();
                finishAffinity();   //finish all previous activity on stack
            }
        });
alertDialog.show();

答案 1 :(得分:0)

每次执行操作时,您都会不断添加活动:

DialogInterface.OnClickListener() {


    @Override
    public void onClick(DialogInterface dialog, int which) {

    Intent i = new Intent(Task1Activity.this, Task1Activity.class);
    startActivity(i);

    }
});

为了保持只有1项活动存活,您应该在开始新活动时finish()旧活动:

DialogInterface.OnClickListener() {


    @Override
    public void onClick(DialogInterface dialog, int which) {

    Intent i = new Intent(Task1Activity.this, Task1Activity.class);
    startActivity(i);
    finish();
    }
});

答案 2 :(得分:0)

我认为问题是startActivity(i); 当您点击确定时,startActivity(i)会在当前Task1Activity上启动另一个Task1Activity,当您按下取消时,顶部Task1Activity正在完成,您将返回上一个{{ 1}}。 用旗帜试试Task1Activity

startActivity(i)