5
  • I have an Activity with 3 Fragments, now each fragment has 2 ToggleButtons(total six buttons).

  • An AlertDialog is shown to the user on each button click.

  • Each button does some different action and so the layouts/views of Alert Dialog differ from each other, and so the positive button click for dialogs too differ, while the negative button click are almost same.

I have implemented the logic in an onButtonPressed method in the Activity as

onButtonPressed(View v){

    switch(v.getId()){
    case R.id.button1:
        // create and show an AlertDialog
    break;
    }
    case R.id.button2:
        // create and show an AlertDialog
    break;
    }
    case R.id.button3:
        // create and show an AlertDialog
    break;
    }
    .
    .
    .
}

This leads to lots of repetitive lines of code, which isn't the best thing AFAIK. I was willing to know if I should keep current implemention, or create a wrapper class something for creating and showing AlertDialogs.

Rachit Mishra
  • 6,101
  • 4
  • 30
  • 51

3 Answers3

10

You can create a class and then extend DialogFragment class and then override its OnCreateDialog() method, then you create a static method to create an instance and pass arguments.

The OnCreateDialog

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
    //set title,message or view ....

    // when you done
    return dialog.create();
}

The static method to put arguments ( Static Factory Pattern Design )

public static CustomAlertDialog newInstance(String title,String message) {
CustomAlertDialog customAD = new CustomAlertDialog();
Bundle args = new Bundle();
args.putString("title", title);
args.putString("message", message);
customAD.setArguments(args);
return customAD;
}

Then you could use it like this

DialogFragment dialog = CustomAlertDialog.newInstance("titulo","message");
dialog.show(/* etc.. */ );
Luis Pena
  • 4,132
  • 2
  • 15
  • 23
2

Modern approach to creating AlertDialogs is actually to wrap them inside DialogFragments, so you need to create a class extending DialogFragment, override its onCreateDialog() method and return an instance of AlertDialog from it. For the purpose of customizing the dialogs you can add a newInstance() method to your DialogFragment as described in this discussion and pass custom parameters to your class.

Community
  • 1
  • 1
Egor
  • 39,695
  • 10
  • 113
  • 130
1

In my case I all my activities extend a common base-activity class called BaseActivity, where I have two overloads for a method called showAlertDialog():-

protected void showAlertDialog(Context context, String title,
                               String msg, DialogButton dialogButton) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(title);
    builder.setMessage(msg);
    Drawable alertDrawable = getResources().getDrawable(R.drawable.alert);
    alertDrawable.setBounds(0, 0, 32, 32);
    builder.setIcon(alertDrawable);
    if (dialogButton != null) {
        if (dialogButton.equals(DialogButton.YES) || dialogButton.equals(DialogButton.OK)) {
            int textId = dialogButton.equals(DialogButton.YES) ? R.string.yesTxt : R.string.ok;
            builder.setPositiveButton(textId, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int id) {
                }
            });
        } else if (dialogButton.equals(DialogButton.NO))
            builder.setNegativeButton(R.string.noTxt, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int id) {
                    onNegativeButtonClicked(dialogInterface, id);
                }
            });
    }
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

protected void showAlertDialog(Context context, String title,
                               String msg, DialogButton dialogButton,
                               DialogButton nxtDialogButton) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(title);
    builder.setMessage(msg);
    Drawable alertDrawable = getResources().getDrawable(R.drawable.alert);
    alertDrawable.setBounds(0, 0, 32, 32);
    builder.setIcon(alertDrawable);
    if (dialogButton != null && nxtDialogButton != null) {
        if (dialogButton.equals(DialogButton.YES) || dialogButton.equals(DialogButton.OK)) {
            int textId = dialogButton.equals(DialogButton.YES) ? R.string.yesTxt : R.string.ok;
            builder.setPositiveButton(textId, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int id) {
                    onPositiveButtonClicked(dialogInterface, id);
                }
            });
        }
        if (nxtDialogButton.equals(DialogButton.NO))
            builder.setNegativeButton(R.string.noTxt, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int id) {
                    onNegativeButtonClicked(dialogInterface, id);
                }
            });
    }
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}  
protected void onPositiveButtonClicked(DialogInterface dialogInterface, int id) {
   //Override this to handle positive button press

}

protected void onNegativeButtonClicked(DialogInterface dialogInterface, int id) {
  //Override this to handle negative button press

}

where DialogButton is defined as :-

public enum DialogButton {
OK, YES, NO

}

Usage :-

showAlertDialog(this, "Heading", "A dialog with one button", DialogButton.OK)

showAlertDialog(this, "Heading", "A dialog with two button", DialogButton.YES, DialogButton.NO)

PS : Instead of using R.string.yesTxt, I could have done a reverse lookup for string in DialogButton enum (thought for some this I didn't realise this at that time).

Siddharth Srivastava
  • 1,059
  • 1
  • 10
  • 22
  • Very good implementation. Should be accepted answer. Just a small add : if the base activity is in another package (let's say an SDK library) the access modifier should be public instead of protected. – BMU Apr 30 '18 at 16:54