在非活动类中创建alertdialog

时间:2015-04-16 07:50:01

标签: java android alertdialog

我有一个实现view.onclicklistener的类。如何从这个不是活动类的类创建一个警告对话框。

我一直收到这个错误。

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

这是我的代码

class LoginView implements View.OnClickListener {
public void onClick(final View v) {
    new AlertDialog.Builder(v.getContext())
                            .setTitle("Delete entry")
                            .setMessage("Are you sure you want to delete this entry?")
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // continue with delete
                                }
                            })
                            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // do nothing
                                }
                            })
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .show();

2 个答案:

答案 0 :(得分:2)

这样做

 private Handler mHandler = new Handler(Looper.getMainLooper());

 @Override
    public void run() {
       // ...
       mHandler.post(new Runnable() {
          public void run() {
              // Create your AlertDialog Here...
          }
       });
       // ...
     }

答案 1 :(得分:0)

在您的课程中尝试此方法:

 public static void showAlert(Activity activity) {


    new AlertDialog.Builder(activity)
                        .setTitle("Delete entry")
                        .setMessage("Are you sure you want to delete this entry?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                            }
                        })
                        .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // do nothing
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
}