× Home Tutorials Training Consulting Products Books Company Donate Contact us

NOW Hiring

Quick links


Using dialogs in Android programming This tutorial describes how to use dialogs in Android applications. It is based on Android Studio and Android 5.0.

1. Using dialogs with DialogFragments

1.1. Using dialogs in Android

To show a dialog in your Activity you use an instance of DialogFragment. A DialogFragment is a fragment that displays a dialog window, floating on top of its activities window. You can either return an existing dialog implementation in your fragment or implement a custom layout to be shown.

1.2. Using existing dialogs

Your DialogFragment can implement the onCreateDialog method and return an existing dialog. The Dialog class is the base class for implementing a dialog. Typically, you use one of its subclasses, e.g., AlertDialog, ProgressDialog, DatePickerDialog or TimePickerDialog.

Android also provides a ProgressDialog, which can be opened via a ProgressDialog.open() method call.

1.3. Custom layout for your DialogFragment

If you want to create your custom dialog, you create a layout file for the dialog. This layout file can be inflated and returns via the onCreateView() method of the fragment.

1.4. Communication to the activity via the DialogFragment

Your implementation of DialogFragment communicates similar to other fragment to the activity. A good practice is that the fragment defines an interface which the activity must implement. The fragment can call back into the activity without knowing the implementation details of the activity.

2. Exercise: Using the DialogFragment class

The following demonstrates the usage of the DialogFragment dialog in an activity. It uses an existing dialog and with a custom layout for the dialog.

2.1. Create project and layout files

Create a new Android project with the com.android.vogella.com.dialogfragmentexample package.

Ensure that the layout file of your activity contains two buttons pointing both to onClick method in their android:onClick property.

Create the following layout file, called fragment_username.xml.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:text="Enter user name" />

        android:inputType="text" />

2.2. Create fragments and adjust activity

Create the following two fragment classes.

package dialogfragmentexample.android.vogella.com.dialogfragmentexample;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

public class MyAlertDialogFragment extends DialogFragment {
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
                // set dialog icon
                // set Dialog Title
                .setTitle("Alert dialog fragment example")
                        // Set Dialog Message
                .setMessage("This is a message")

                // positive button
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "Pressed OK", Toast.LENGTH_SHORT).show();
                // negative button
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "Cancel", Toast.LENGTH_SHORT).show();
package dialogfragmentexample.android.vogella.com.dialogfragmentexample;

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

public class MyDialogFragment extends DialogFragment implements TextView.OnEditorActionListener {

    private EditText mEditText;

    public interface UserNameListener {
        void onFinishUserDialog(String user);

    // Empty constructor required for DialogFragment
    public MyDialogFragment() {


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_username, container);
        mEditText = (EditText) view.findViewById(R.id.username);

        // set this instance as callback for editor action
        getDialog().setTitle("Please enter username");

        return view;

    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // Return input text to activity
        UserNameListener activity = (UserNameListener) getActivity();
        return true;

Change the code of your activity to the following listing.

package dialogfragmentexample.android.vogella.com.dialogfragmentexample;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity implements MyDialogFragment.UserNameListener {

    protected void onCreate(Bundle savedInstanceState) {

    public void onFinishUserDialog(String user) {
        Toast.makeText(this, "Hello, " + user, Toast.LENGTH_SHORT).show();

    public void onClick(View view) {
        // close existing dialog fragments
        FragmentManager manager = getFragmentManager();
        Fragment frag = manager.findFragmentByTag("fragment_edit_name");
        if (frag != null) {
        switch (view.getId()) {
            case R.id.showCustomFragment:
                MyDialogFragment editNameDialog = new MyDialogFragment();
                editNameDialog.show(manager, "fragment_edit_name");
            case R.id.showAlertDialogFragment:
                MyAlertDialogFragment alertDialogFragment = new MyAlertDialogFragment();
                alertDialogFragment.show(manager, "fragment_edit_name");

2.3. Test dialog usage

If you run your application and click the corresponding button, your dialog should get displayed.

3. About this website

4. Android Resources

4.1. vogella GmbH training and consulting support


The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.

The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.

Copyright © 2012-2016 vogella GmbH. Free use of the software examples is granted under the terms of the EPL License. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.