Creating a Custom Dialog With AlertDialog.Builder
A custom dialog is useful when an Android app needs a focused interaction without opening another screen. Instead of limiting users to a title and a few lines of text, you can place an input field, dropdown, image, checkbox, or other UI component inside an AlertDialog.
This approach suits practical Android projects such as adding a contact, filtering a ListView, choosing a reminder time, or confirming a purchase. For an Australian audience, a compact dialog can work well when someone is checking an app during a Sydney train trip or using a phone in a busy Melbourne café.
The AlertDialog.Builder class creates the dialog shell, while a separate XML layout controls its appearance. Keeping those responsibilities separate makes the interface easier to maintain and allows the same custom view to be reused in different parts of an app.
This tutorial uses Java and standard Android views. The same design principles apply when building a form for users in Brisbane, Perth, or regional areas where reliable, clear interactions matter and an app may be used on a wide range of Android handsets.
Plan The Custom Dialog Layout
Start by creating a layout resource in res/layout, such as dialog_user_input.xml. A vertical container with padding gives the dialog a clean structure. Add only the controls needed for the task, because a dialog that grows beyond the screen becomes difficult to use.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<EditText
android:id="@+id/nameInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="textPersonName" />
<EditText
android:id="@+id/phoneInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:hint="Phone number"
android:inputType="phone" />
</LinearLayout>
Use descriptive hints and suitable input types so Android can display the correct keyboard. An Australian phone field might accept a mobile number beginning with 04, but validation should still be flexible enough to handle spaces and international formats such as +61.
Inflate The Custom View
In an activity or fragment, inflate the XML layout with a LayoutInflater. The inflated view is then supplied to the builder through setView(). This is the key step that changes a standard alert into a custom dialog.
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_user_input, null);
EditText nameInput = dialogView.findViewById(R.id.nameInput);
EditText phoneInput = dialogView.findViewById(R.id.phoneInput);
If the code is inside a fragment, use the fragment’s context carefully:
View dialogView = inflater.inflate(R.layout.dialog_user_input, null);
The inflater should generally come from the current activity or a valid context connected to the screen. Avoid using an application context for a dialog because it may not have the correct theme or window relationship.
Create The AlertDialog Builder
Create an AlertDialog.Builder, set a title, attach the custom view, and define positive and negative buttons. Calling create() returns the configured dialog, while show() creates and displays it immediately.
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add contact")
.setView(dialogView)
.setNegativeButton("Cancel", null)
.setPositiveButton("Save", null)
.create();
dialog.show();
The buttons can be assigned listeners directly, but validation is often easier after the dialog has been shown. By default, a positive button dismisses the dialog as soon as it is pressed. That behaviour is inconvenient when invalid input should keep the form open.
You can replace the default click listener and validate the fields manually:
dialog.setOnShowListener(listener -> {
Button saveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
saveButton.setOnClickListener(view -> {
String name = nameInput.getText().toString().trim();
String phone = phoneInput.getText().toString().trim();
if (name.isEmpty()) {
nameInput.setError("Enter a name");
return;
}
if (phone.isEmpty()) {
phoneInput.setError("Enter a phone number");
return;
}
saveContact(name, phone);
dialog.dismiss();
});
});
This pattern keeps the dialog visible when a field is incomplete. It is suitable for forms that save to SQLite, update a RecyclerView, or trigger another app operation after successful validation.
Add Actions And Accessibility
A custom dialog should have one clear primary action. Use labels such as “Save”, “Apply”, or “Choose” instead of vague text like “OK” when the button performs a specific task. A negative button should cancel without changing stored data.
For accessibility, provide useful hints, readable contrast, and a sensible focus order. Do not rely on colour alone to show an error. setError() supplies a message that can also be announced by accessibility services, while labels and content descriptions help users who navigate with TalkBack.
Dialogs are also useful for small notification preferences, such as choosing whether to receive updates from a service using Firebase Cloud Messaging. Keep notification choices explicit, and avoid presenting a permission-like request without explaining why the setting matters.
Manage Dialog State Safely
A dialog belongs to the activity or fragment that displays it, so avoid holding a long-lived reference to an old activity. Recreating the screen during rotation can make a stored dialog reference invalid. For more complex flows, use a DialogFragment, which integrates better with lifecycle changes.
If the form contains temporary values, save them when needed and restore them after configuration changes. A simple one-off confirmation may not require this extra work, but a multi-field form should not unexpectedly lose data when a device rotates or switches between portrait and landscape.
Test the dialog on small and large screens, including devices with gesture navigation and different font scales. Australians commonly use Android phones from Samsung, Google, Motorola, and lower-cost brands sold through retailers and carriers such as Telstra, Optus, and Vodafone, so hard-coded widths are more likely to cause problems than responsive layouts.
Compare Common Dialog Approaches
Choose a standard alert when the message is short and the available actions are simple. Use a custom AlertDialog.Builder view when the user needs to enter or select information without leaving the current context. For a longer workflow, a separate activity or bottom sheet may provide better space and navigation.
The builder pattern also works well in beginner projects because each part is visible: the layout defines the controls, the builder defines the shell, and the button listener handles the result. Developers looking for broader study material can use an Android learning resource alongside practical projects involving SQLite, preferences, and UI components.
| Approach | Best For | Main Advantage | Main Limitation |
|---|---|---|---|
Standard AlertDialog |
Short messages and confirmations | Fast to implement | Limited customisation |
Custom AlertDialog.Builder |
Small forms and selections | Flexible layout with familiar dialog actions | Can become crowded |
DialogFragment |
Dialogs affected by lifecycle changes | Better state and rotation handling | Requires more structure |
| Separate activity | Long or multi-step forms | More room for content | Takes the user away from the current screen |
| Bottom sheet | Contextual tools and mobile actions | Comfortable for touch interaction | Not ideal for every confirmation flow |
A well-designed custom dialog should be brief, readable, and focused on one decision. With an XML layout, an inflated view, and a carefully handled AlertDialog.Builder, you can create a reusable interaction that fits naturally into an Android application.