0

How do I build an AlertDialog once and for all. I'll show it as at when needed all through the activity.

Faraday
  • 327
  • 1
  • 6
  • 19

2 Answers2

2

You can create a method in any Util class as -

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

And call from the activity anytime you want by calling -

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

For alert dialog with action buttons -

Declare the dialog outside any method -

private AlertDialog dialog;

You can create the dialog in Activity's onCreate() like this -

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();

and whenever you want to show it you can show like this -

 dialog.show();
Shadab Ansari
  • 7,022
  • 2
  • 27
  • 45
0

I use this class

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

You use new ModalDialog (this, "Example")

I hope this helps :)

in doModal () method should check this end

if (android.os.Build.VERSION.SDK_INT <Build.VERSION_CODES.LOLLIPOP) {
   msg.recycle ();
}
Marco Giovanni
  • 297
  • 7
  • 18