如何创建我可以在 Activity 期间使用的 AlertDialog

How to Create An AlertDialog that I can use throughout an Activity

如何一劳永逸地构建 AlertDialog。我将在整个 activity 期间在需要时显示它。

您可以在任何 Util class 中创建方法,如 -

public static void showDialog(Context context, int msgResId) {
        if (context == null) return;
        new AlertDialog.Builder(context)
                .setMessage(msgResId)
                .create()
                .show();
    }

然后随时从 activity 调用 -

showDialog(MainActivity.this, R.string.your_string_res_id);

对于带有操作按钮的警报对话框 -

在任何方法之外声明对话框 -

private AlertDialog dialog;

您可以像这样在 Activity 的 onCreate() 中创建对话框 -

dialog = new AlertDialog.Builder(MainActivity.this)
                .setMessage("Your message")
                .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       //Your code
                    }
                })
                .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       //Your code
                })
                .create();

而且无论什么时候你想展示它你都可以这样展示-

 dialog.show();

我用这个class

https://github.com/mauricioj/gals/blob/master/GalsM/src/br/ufscar/sigam/util/ModalDialog.java

你使用了新的ModalDialog(这个,"Example")

希望对您有所帮助:)

在doModal()方法中应该检查这一端

if (android.os.Build.VERSION.SDK_INT <Build.VERSION_CODES.LOLLIPOP) {
   msg.recycle ();
}