2011-03-03 28 views
0

我想从另一个类调用警告对话框,但这不让我将它设置为静态。它表明只有最后一个被允许,这意味着它不能从另一个类中调用它。我不确定我是否正确地做了这件事,或者甚至有可能。我有2类警告对话框:从另一个类调用警报对话

static final AlertDialog.Builder alertbox = new AlertDialog.Builder(this); 
      alertDialog = new AlertDialog.Builder(this).create(); 

     alertbox.setTitle("Hello"); 
     alertbox.setMessage("Press Continue or Cancel"); 
     alertbox.setPositiveButton("CONTINUE", 
       new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface dialog, int which) { 


        } 
       }); 

     alertbox.setNegativeButton("CANCEL", 
       new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface dialog, int which) { 

        } 
       }); 

     alertDialog.setIcon(R.drawable.icon); 

然后,这被调用到Class:

QuizValidation.alertbox.show(); 

其中也解决不了。

如果我可以将类2中的alertbox设置为静态,我可以对其进行排序。

将不胜感激任何意见。

感谢

+0

你为什么试图在另一个类中定义警报? – 2011-03-03 16:47:39

+0

我将需要一些提醒进行验证,并且不想填写该课程。 – Raj 2011-03-03 16:48:30

+0

使用共同的父类:-) – 2011-03-03 16:52:03

回答

2

它是一个更好的主意来定义一个基类所有的对话,让我们把它叫做......嗯BaseActivity

Class BaseActivity extends Activity{ 

int DIALOG_X = 1; 
int DIALOG_Y = 2; 
int DIALOG_Z = 3; 
// More Dialog identifiers 

ProgressDialog progressDialog; 
AlertDialog alertDialog; 
//More dialog objects if you need 

protected Dialog onCreateDialog(int id) { 
    Dialog dialog; 
    switch(id) { 
    case DIALOG_X: 
     // do the work to define the X Dialog 
     break; 
    case DIALOG_Y: 
     // do the work to define the Y Dialog 
     break; 
    default: 
     dialog = null; 
    } 
    return dialog; 
} 
} 

然后在另一个类扩展BaseActivity并调用

showDialog(DIALOG_X); 

当你需要显示Dialog_X

+0

我不能从主类扩展类。如果我扩展它,这已经使用了一堆类并显示错误。它也使用全局应用程序。感谢您的帮助,我现在就把它留在那里。 – Raj 2011-03-03 17:39:51

+0

我总是为我的项目做基础类,但从来没有想过它。谢谢 – Rohit 2014-05-23 06:36:30

0

你也可以si mply扩展AlertDialog,并使你自己和重用。

2

创建一个Constructor,您可以在其中获得活动。这样的 -

Activity activity; 
public YourClass (Activity activity){ 
     this.activity = activity; 
} 

现在,用这个activity作为参数 -

AlertDialog.Builder adb=new AlertDialog.Builder(activity);

因为不能只用context显示对话框。你需要为此提供一个Activity