What's the best way to have reusable dialog bo

2019-07-04 21:40发布

问题:

What's the best way to create reusable dialog boxes in Android?

Reading through the Dialog dev guide, I know I can use AlertDialog.Builder(this); in one of my Activitys, but what if I want to use this in multiple Activities? If this was some other class I would extend it, so MyDialog extends AlertDialog, but then I cannot use the Builder.

Any suggestions?

回答1:

Crate one class file like as AllMethod.java and add this code in that class file.

public static void showAlert(Activity act, String msg, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder alert = new AlertDialog.Builder(act);
        alert.setMessage(msg);
        alert.setPositiveButton("OK", listener);
        alert.show();
    }

and you can use from any class like below code.

AllMethod.showAlert(mActivity, "", new DialogInterface.OnClickListener() {
        @Override
         public void onClick(DialogInterface dialog, int which) {
         // Do your code for click
         }
});