java - 尝试设置 AlertDialog 但不断出现错误

标签 java android android-alertdialog

我试图为用户设置一个警报对话框,以确认您想要发生什么事情,但我不确定如何设置它,所以我环顾四周并找到了如何设置它,但我仍然不断得到错误

  AlertDialog.Builder builder = new AlertDialog.Builder(settings.this)
.setTitle("hello")
.setButton("OK", new DialogInterface.OnClickListener() {
 //^^^^^^^it keeps telling me "The method setButton(String, new DialogInterface.OnClickListener(){}) is undefined for the type AlertDialog.Builder"

public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK",Toast.LENGTH_SHORT).show();
                                        }
                                });





}

最佳答案

我建议您创建自己的警报类。使用起来会更加方便。我的警报类如下:

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class Alert {

  private Context ctx;

  public Alert(Context ctx) {
    this.ctx = ctx;
  }

  public void show(String str) {
    build(str);
  }

  public void show(int str) {
    build(String.valueOf(str));
  }

  public void close(AlertDialog alert) {
    alert.dismiss();
  }

  private void build(String str) {
    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);

    builder.setMessage(str);

    builder.setCancelable(false);
    builder.setTitle("Info");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int id) {

      }
    });

    AlertDialog alert = builder.create();
    alert.show();
  }
}

您可以按如下方式使用此类:

Alert alert = new Alert(SaveAndGoBack.this);
alert.show('bla bla bla');

关于java - 尝试设置 AlertDialog 但不断出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25433181/

相关文章:

java - 将java代码转换为c#

Android UI tester monkey - 没有发现要运行的 Activity

android - 如何使用新的 Google Analytics for mobile (v2) 分析 Android 服务任务

Android 服务在应用程序内或应用程序外弹出

java - Eclipse 控制台中的 Windows-1250

java - 更改 JAX-WS 默认 XML 命名空间前缀

android - 如何从我的 Android 版本中删除导航栏?

Android:如何以编程方式设置对话框上按钮的文本大小?

android - 如何自定义警报对话框以使按钮适合警报对话框

java - EHCache 对原始元素的更改