Support free tutorials

Quick links

Showing dialogs in Android with fragments - Tutorial

Lars Vogel

Version 10.0


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

Table of Contents

1. Using dialogs in Android with DialogFragments
1.1. Using dialogs in Android
1.2. Using existing dialogs
1.3. Custom layout for your DialogFragment
1.4. Communication to the activity via the DialogFragment
2. Exercise: Using the DialogFragment class
2.1. Target
2.2. Create project and layout files
2.3. Create fragments and adjust activity
2.4. Test dialog usage
3. About this website
4. Links and Literature
4.1. Android Resources
4.2. vogella GmbH training and consulting support

1. Using dialogs in Android with DialogFragments

1.1. Using dialogs in Android

In the past you could open dialogs from your activity via the showDialog(int) method but since the introduction of fragments which method has been deprecated. You should use an instance of DialogFragment to show a dialog. A DialogFragment is a fragment that displays a dialog window, floating on top of its activity’s 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 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 so that the fragment can call back into the activity without knowing the implementation details of the activity.

2. Exercise: Using the DialogFragment class

2.1. Target

The following demonstrates the usage of the DialogFragment dialog in an activity. Both ussages are demonstrates, the usage of an existing dialog and a custom layout.

2.2. Create project and layout files

Create a new Android project with the 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=""

        android:text="Enter user name" />

        android:inputType="text" />

2.3. Create fragments and adjust activity

Create the following two fragment classes.


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();


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(;

        // 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.


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()) {
                MyDialogFragment editNameDialog = new MyDialogFragment();
      , "fragment_edit_name");
                MyAlertDialogFragment alertDialogFragment = new MyAlertDialogFragment();
      , "fragment_edit_name");

2.4. Test dialog usage

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

3. About this website

4. Links and Literature

4.1. Android Resources

Android Dialogs standard documentation.

4.2. 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.