Search code examples
javaandroidandroid-alertdialog

How can I handle the click listener inside the static method?


It is very boring to initialize AlertDialog every time I want to use it, I have a lot of activities that use AlertDialog so I want to simplify that and create a class to initialize AlertDialog and show it when I want.

Here is the DialogManager class that I created:

public class DialogManager {

    private static AlertDialog.Builder builder;

    public static void show(Context context, int themeResId, String title, String message, String positiveButtonText) {
        builder = new AlertDialog.Builder(context, themeResId)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(positiveButtonText, null);
        builder.show();
    }

    public static void show(Context context, int themeResId, String title, String message, String positiveButtonText, String negativeButtonText) {
        builder = new AlertDialog.Builder(context, themeResId)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(positiveButtonText, null)
                .setNegativeButton(negativeButtonText, null);
        builder.show();
    }

}

Everything works well but I faced a problem with the click listener, How can I handle the click listener because every activity will treat the button in its way.

How can I handle that?


Solution

  • setPositiveButton takes DialogInterface.OnClickListener as a second param, so just add it as a method parameter

    public static void show(Context context, int themeResId, String title, String message,
            String positiveButtonText,
            DialogInterface.OnClickListener positiveCallback) {
        show(context, themeResId, title, message,
            positiveButtonText, positiveCallback,
            null, null); // no negative in this case
    }
    
    public static void show(Context context, int themeResId, String title, String message,
            String positiveButtonText,
            DialogInterface.OnClickListener positiveCallback,
            String negativeButtonText,
            DialogInterface.OnClickListener negativeCallback) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context, themeResId)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(positiveButtonText, positiveCallback);
        if (negativeButtonText!=null) {
            builder.setNegativeButton(negativeButtonText, negativeCallback);
        }
        builder.show();
    }
    

    and don't overuse static keyword, keeping static Builder on top of this files isn't proper approach (in some cases it may lead to memory leak, probably also in your case), so remove below line and keep only local builder unti you call builder.show()

    private static AlertDialog.Builder builder;