java - 无法让 Android 应用程序退出

标签 java android android-alertdialog

我正在努力让我的 Android 应用程序通过警报对话框退出。

点击"is"再次播放效果很好,因为它会重新启动应用程序,您可以再次播放。

不幸的是,当我点击“否”时,它只是删除了对话框警告框,我不知道为什么。

非常感谢任何帮助。

谢谢

@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();

最佳答案

您正在创建 Activity Intent i = new Intent(Task1Activity.this, Task1Activity.class);,它将 Activity 添加到堆栈上。

试试这段代码:

 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();

关于java - 无法让 Android 应用程序退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42299621/

相关文章:

c# - 在 Java 程序中调用 C# 方法

java - 删除数组中的第一个或最后一个索引而不出现 "Out of Bounds"错误

Android 1.6 模拟器崩溃

android - Android Studio中Gradle构建的问题

java - 用 View (按钮)覆盖 Android AlertDialog

java - MySQL 连接 - java.sql.SQLException : Unable to connect to any hosts due to exception

java - 如何使用 OdfToolkit 打印 OpenDocument 文本?

android - clientID 有什么用?

listview - 如何在 Flutter 中过滤 AlertDialog 中 ListView 中的数据?

android - 在警报对话中自定义 Android 对讲?