Visit Sponsor

Written by 8:30 am Android

Android DialogFragment Example – Create and Use Custom Dialogs

In modern Android development, DialogFragment is the recommended way to create and display dialogs. It integrates with the FragmentManager and handles lifecycle events cleanly, avoiding memory leaks and configuration issues that classic dialogs often suffer.

This guide explains how to implement a DialogFragment with custom layout, listeners, and data communication – using best practices aligned with AndroidX and Jetpack patterns.

What Is DialogFragment?

DialogFragment is a subclass of Fragment designed to display a dialog window inside an Activity or another Fragment. It manages its own lifecycle, making it:

  • Configurable during rotation
  • Safe from memory leaks
  • Easy to reuse
  • Lifecycle aware for modern UI patterns

It replaces the older Dialog API in most use cases.

When to Use DialogFragment

Use DialogFragment when:

  • You need a modal prompt (confirmation, input form)
  • You want a custom layout inside a dialog
  • You need to handle configuration changes safely
  • You want to pass data in/out of the dialog

Avoid DialogFragment for full-screen UI — in that case choose a regular Fragment or Activity.

Add Dependencies

Make sure you use AndroidX Fragment library:

dependencies {
    implementation "androidx.fragment:fragment-ktx:1.6.0"
}

Use the latest stable fragment version available.

Create a DialogFragment Class

Create a custom class extending DialogFragment:

public class MyAlertDialogFragment extends DialogFragment {

    public interface DialogListener {
        void onPositiveClick(String input);
        void onNegativeClick();
    }

    private DialogListener listener;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof DialogListener) {
            listener = (DialogListener) context;
        } else {
            throw new ClassCastException(context.toString()
                    + " must implement DialogListener");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());

        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_custom, null);

        EditText etInput = view.findViewById(R.id.etDialogInput);

        builder.setView(view)
               .setTitle("Enter Value")
               .setPositiveButton("OK", (dialog, id) -> {
                   String value = etInput.getText().toString().trim();
                   listener.onPositiveClick(value);
               })
               .setNegativeButton("Cancel", (dialog, id) -> {
                   listener.onNegativeClick();
               });

        return builder.create();
    }
}

Here:

  • We create a listener interface to communicate results
  • Inflate a custom layout inside the dialog
  • Handle OK/Cancel via listener callbacks

Create Custom Dialog Layout

Define your custom UI in dialog_custom.xml:

<?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="16dp">

    <EditText
        android:id="@+id/etDialogInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Type here"/>
</LinearLayout>

This creates a simple dialog UI with an input field.

Show DialogFragment from Activity

In your Activity (implementing the listener):

public class MainActivity extends AppCompatActivity
        implements MyAlertDialogFragment.DialogListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void showDialog(View view) {
        MyAlertDialogFragment dialog = new MyAlertDialogFragment();
        dialog.show(getSupportFragmentManager(), "MyDialog");
    }

    @Override
    public void onPositiveClick(String input) {
        Toast.makeText(this, "You entered: " + input, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNegativeClick() {
        Toast.makeText(this, "Cancel pressed", Toast.LENGTH_SHORT).show();
    }
}

This demonstrates:

  • Showing the dialog
  • Handling user input via listener callbacks

Passing Data to DialogFragment

You can pass initial data into the dialog using arguments:

Bundle args = new Bundle();
args.putString("title", "Update Value");
dialog.setArguments(args);

Inside the DialogFragment:

String title = getArguments().getString("title");
builder.setTitle(title);

This allows dynamic customization.

DialogFragment with Full-Screen Style

For larger content, you can style your DialogFragment to fullscreen:

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
        dialog.getWindow().setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);
    }
}

This ensures the dialog occupies the full screen.

Handling Rotation and Lifecycles

DialogFragments survive configuration changes by default when shown via show(). This avoids dismiss-and-recreate flickering that classic dialogs suffer.

Use setRetainInstance(true) if you need to retain internal state.

Best Practices

From real Android engineering experience:

  • Always use DialogFragment over deprecated Dialog for modern apps
  • Avoid heavy work on dialog UI thread
  • Use ViewBinding or DataBinding for safer view access
  • Validate user input before callback invocation

These practices lead to robust, maintainable dialog interactions.

Common Issues and Fixes

Dialog not showing?
✔ Check you call dialog.show(getSupportFragmentManager(), TAG)

Crash on attach?
✔ Ensure host implements the listener interface

View binding null errors?
✔ Use proper view inflation techniques or ViewBinding

Summary

DialogFragment is the recommended way to present dialogs in Android apps. With lifecycle safety, custom layouts, and clean callbacks, it makes modal interactions predictable and maintainable. Use it for confirmations, input forms, and modal content in your UI flows.

Visited 6 times, 1 visit(s) today
Close