Calling an alert dialog from another class
I am trying to call an alert dialog from another class but this is not letting me set it to static. It shows as only final is permitted and that means it cannot call it from the other class. I'm not sure 开发者_JAVA百科if I am doing it correctly or if it is even possible. I have the alert dialog in class 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);
This then gets called in class1:
QuizValidation.alertbox.show();
Which also cannot be resolved.
I can probably sort that out if I could set the alertbox in class 2 to static.
Would appreciate any advice.
Thanks
Its a better idea to define all your dialogs in a base class , lets call it ... well 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;
}
}
Then in another class extend BaseActivity and call
showDialog(DIALOG_X);
when you need to show Dialog_X
Create a Constructor
, where you can get Activity. Like this -
Activity activity;
public YourClass (Activity activity){
this.activity = activity;
}
Now, use this activity
as argument -
AlertDialog.Builder adb=new AlertDialog.Builder(activity);
Because dialog can't be shown using just a context
. You need to provide an Activity
for that.
You can also simply extend AlertDialog, and make your own and reuse.
精彩评论