How do I build an AlertDialog once and for all. I'll show it as at when needed all through the activity.
            Asked
            
        
        
            Active
            
        
            Viewed 48 times
        
    0
            
            
        - 
                    Consider using a Toast instead unless you want to force the user to acknowledge the alert message. – Dale Wilson Apr 05 '16 at 19:24
 - 
                    Yes, the user need to take actions with the negative and positive buttons. – Faraday Apr 05 '16 at 19:26
 
2 Answers
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
 
- 
                    I'll configure everything about the dialog in the util class and this includes the negative and positive buttons. How do I show it in MainActivity. – Faraday Apr 05 '16 at 19:31
 - 
                    
 
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