Search code examples
androiddialogandroid-alertdialogbuilder

What is the significance of AlertDialog.Builder class?


In Android every dialog is shown using Builder for that dialog class. The Builder is the static inner class in these classes. So why the Builder is given the control to build the dialog? Thanks in advance.


Solution

  • It is just a helper class which allows you to call methods in a chain and set positive/negative buttons easily. For example:

    AlertDialog.Builder

    AlertDialog.Builder alert = new AlertDialog.Builder(this)
      .setTitle("this is title")
      .setMessage("this is message")
      .setCancelable(false)
      .setPositiveButton("OK", null);
      alert.show();
    

    AlertDialog

    AlertDialog alert2 = new AlertDialog.Builder(this).create();
    alert2.setTitle("this is title");
    alert2.setMessage("");
    alert2.setCancelable(false);
    alert2.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // null 
        }
    });
    alert2.show();
    

    So now you may see the difference in ease of creating same thing with two different ways.