java - 如何 Intent Activity 使用AlertDialog?

标签 java android dialog

public void Home (View view){
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Back");
    dialog.setIcon(R.drawable.logo);
    dialog.setCancelable(true);
    dialog.setMessage("Do you want to go back?");
    dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }

    });

    dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    dialog.show();
}

现在,当我单击“Home”按钮时,我停留在 pageOne.java 上。我想返回 MainActivity.java,但出现错误。

enter image description here

最佳答案

您对this的使用有问题:

new Intent(this, MainActivity.class);

在该范围内,它认为 this 引用的是匿名内部类 DialogInterface.OnClickListener。因此,您应该使用对外部类实例的引用,例如 HomeActivity.this (或任何您的 Activity 的名称)。

new Intent(HomeActivity.this, MainActivity.class);

关于java - 如何 Intent Activity 使用AlertDialog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34803381/

相关文章:

java - 使用一个类的多个constrictor在firebase中存储数据

java - 如何创建所有实现特定接口(interface)的类对象列表?

java - java中的监听器是如何工作的?

java - 使用 Android 执行 RESTful URL

Android 将数据从对话框传递到弹出对话框的屏幕

java - JavaFX 中的彩色图标字体

android - 从资源android中随机化字符串

android - 如何垂直拉伸(stretch) GridView 的单元格?

java - 如何处理 WebView 中的 JavaScript 对话框弹出

qt - 单击并按住标题移动对话框