Search code examples
androidandroid-alertdialogandroid-dialogfragment

Can anyone explain me what is better solution for creating an AlertDialog in the android app development?


What is the better solution of creating an AlertDialog in the android app development:

  1. Creating an AlertDialog with AlertDialog.Builder in the fragment(class extends DialogFragment)
  2. Creating an AlertDialog with AlertDialog.Builder without fragment

Solution

  • It depends,

    By simplicity, I always create an standar AlertDialog like this:

       AlertDialog.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
           builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
        } else {
           builder = new AlertDialog.Builder(this);
        }
        builder.setMessage(getString(R.string.message))
        .setPositiveButton(getString(R.string.ready), new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
             }
        })
    
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setCancelable(true)
    .show();
    

    But you can extend DialogFragment class if you want to build more functions and capabilities within the dialog like adding a list and execute your custom click functions,

    Hope it helps