SoFunction
Updated on 2025-04-14

Detailed explanation of the use of Dialog in Android

Detailed explanation of the use of Dialog in Android

Dialog is a commonly used UI component in Android, used to temporarily display important information or obtain user input.

1. Basic Dialog Type

1.1 AlertDialog (Warning Dialog)

The most commonly used dialog box type, you can set titles, messages, buttons, etc.:

new (this)
    .setTitle("hint")
    .setMessage("Are you sure you want to delete this item?")
    .setPositiveButton("Sure", new () {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // Confirm button click event        }
    })
    .setNegativeButton("Cancel", null)
    .setNeutralButton("Reminder later", null)
    .show();

1.2 ProgressDialog (Progress dialog box, abandoned)

⚠️ Note: ProgressDialog is abandoned in API 26, so it is recommended to use ProgressBar

Alternatives:

// Implement in layout using ProgressBar builder = new (this);
(.progress_dialog_layout);
AlertDialog dialog = ();
();

1.3 DatePickerDialog/TimePickerDialog (Date/Time Selection dialog box)

// Date selection dialog boxDatePickerDialog datePickerDialog = new DatePickerDialog(this, 
    new () {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            // Process the selected date        }
    }, 2023, 0, 1); // Initial year, month, day();
// Time selection dialog boxTimePickerDialog timePickerDialog = new TimePickerDialog(this,
    new () {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // Process the time of selection        }
    }, 12, 0, true); // Initial hours and minutes, whether it is 24-hour system();

2. Customize Dialog

2.1 Using a custom layout

 builder = new (this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = (.custom_dialog_layout, null);
(dialogView);
// Get the controls in the custom layoutEditText editText = (.dialog_edittext);
Button button = (.dialog_button);
AlertDialog dialog = ();
();
(v -> {
    String input = ().toString();
    // Process input    ();
});

2.2 Inherit the Dialog class to create a fully customized dialog box

public class CustomDialog extends Dialog {
    public CustomDialog(@NonNull Context context) {
        super(context);
        setContentView(.custom_dialog_layout);
        Button closeButton = findViewById(.close_button);
        (v -> dismiss());
        // Set dialog window properties        Window window = getWindow();
        if (window != null) {
            (new ColorDrawable());
             params = ();
             = .MATCH_PARENT;
             = .WRAP_CONTENT;
            (params);
        }
    }
}
// useCustomDialog customDialog = new CustomDialog();
();

3. DialogFragment (recommended method)

DialogFragment is a better way to manage the life cycle of a dialog, especially when Activity rebuilds:

public class MyDialogFragment extends DialogFragment {
    // The dialog box logic will be implemented here}

Method 1: Use custom layout (rewrite onCreateView)

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate custom layout    View view = (.fragment_dialog, container, false);
    // Initialize the view component    Button button = ();
    (v -> {
        // Handle click events        dismiss(); // Close the dialog box    });
    return view;
}

Show dialog in Activity:

MyDialogFragment dialogFragment = new MyDialogFragment();
(getSupportFragmentManager(), "MyDialogFragment");

Use AlertDialog (rewrite onCreateDialog)

useAlertDialog(RewriteonCreateDialog)
public class MyDialogFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
         builder = new (getActivity());
        ("DialogFragment Example")
               .setMessage("This is a dialog created using DialogFragment")
               .setPositiveButton("Sure", (dialog, id) -> {
                   // Confirm button click event               })
               .setNegativeButton("Cancel", (dialog, id) -> {
                   // Cancel button click event               });
        return ();
    }
}
// Show DialogFragmentMyDialogFragment dialogFragment = new MyDialogFragment();
(getSupportFragmentManager(), "my_dialog_tag");

DialogFragment with parameters

public class CustomDialogFragment extends DialogFragment {
    private static final String ARG_TITLE = "title";
    private static final String ARG_MESSAGE = "message";
    public static CustomDialogFragment newInstance(String title, String message) {
        CustomDialogFragment fragment = new CustomDialogFragment();
        Bundle args = new Bundle();
        (ARG_TITLE, title);
        (ARG_MESSAGE, message);
        (args);
        return fragment;
    }
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle args = getArguments();
        String title = args != null ? (ARG_TITLE) : "";
        String message = args != null ? (ARG_MESSAGE) : "";
        return new (getActivity())
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("OK", null)
                .create();
    }
}
// useCustomDialogFragment dialog = ("title", "Message Content");
(getSupportFragmentManager(), "custom_dialog");

4. Dialog styles and themes

4.1 Using a custom theme

Defined in:

<style name="CustomDialogTheme" parent="">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
</style>

Use topics:

 builder = new (this, );

4.2 Set dialog box width and animation

AlertDialog dialog = ();
();
// Set the dialog box widthWindow window = ();
if (window != null) {
    (.MATCH_PARENT, .WRAP_CONTENT);
    // Set animation    ();
}

5. Dialog Lifecycle Management

Use DialogFragment to better manage dialog lifecycles:

public class LifecycleDialogFragment extends DialogFragment {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        (savedInstanceState);
        // Initialization operation    }
    @Override
    public void onStart() {
        ();
        // Operation when the dialog box is displayed    }
    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        (dialog);
        // Operation when the dialog box is closed    }
    @Override
    public void onCancel(@NonNull DialogInterface dialog) {
        (dialog);
        // The operation when the user presses the return key or clicks external cancellation    }
}

6. Best Practices

  • Preferential use of DialogFragment: It handles configuration changes and life cycles better than using Dialog directly
  • Avoid blocking operations: Do not perform time-consuming operations in the dialog button click event
  • Keep it simple: Dialog box should focus on a single task
  • Consider accessibility: Add appropriate content description and focus management to the dialog box
  • Test different scenarios: Including dialog box behavior in case of rotating devices, low memory, etc.

This is the end of this article about Android: Dialog usage. For more information about Android Dialog usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!