从非活动类调用对话框?

时间:2014-06-01 10:57:23

标签: java android

我试图从另一个类中调用对话框

public void alertbox() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);    
    builder.setMessage("Blah").setCancelable(false);
    setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        }); 
    AlertDialog alert = builder.create(); alert.show();
}

我从我的班级调用这个方法,但是我的应用程序崩溃了,有人可以告诉我为什么吗?

2 个答案:

答案 0 :(得分:2)

您需要Application context才能在单独的课程中显示此Alert Dialog。有两种方法可以实现这一点。

  1. 直接将context传递给您的alertbox(context)方法

  2. 创建single argument constructor并在其上传递context

  3. 下面我看到你第二种方式将context传递给single argument constructor

    public class AlertMessages {
        Context context;
    
        public AlertMessages(Context con) {
            this.context=con;
        }
    
        public void alertbox() {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);            
            builder.setMessage("Blah")
                    .setCancelable(false)
                    .setNeutralButton("Ok", new DialogInterface.OnClickListener() { 
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        }); 
            AlertDialog alert = builder.create(); 
            alert.show();
        } 
    }
    

    然后,在AlertMessages中使用此Activity课程,如下所示:

    AlertMessages msg = new AlertMessages(youractivity.this);
    msg.alertbox();
    

答案 1 :(得分:-1)

使用此表格:

new AlertDialog.Builder(this)
.setTitle("MessageDemo")
.setMessage("eek!")
.setNeutralButton("Close", new DialogInterface.OnClickListener()
{
 public void onClick(DialogInterface dlg, int sumthin)
 {
  // do nothing – it will close on its own
 }
})
.show();

作为在onCreateView()中提供视图的替代方法,您可以覆盖 onCreateDialog()并提供一个对话框instance.below代码提供示例代码 这种方法。

以下代码。覆盖DialogFragment的onCreateDialog()

MyDialogFragment
 {
    .....other functions
   @Override
   public Dialog onCreateDialog(Bundle icicle)
    {
       AlertDialog.Builder b = new AlertDialog.Builder(getActivity())
      .setTitle("My Dialog Title")
      .setPositiveButton("Ok", this)
      .setNegativeButton("Cancel", this)
      .setMessage(this.getMessage());
       return b.create();
    }
    .....other functions
 }
相关问题