× Home Tutorials Training Consulting Products Books Company Donate Contact us









NOW Hiring

Quick links

Share

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. Displaying dialogs with DialogFragments

1.1. Using fragments for dialogs

A DialogFragment is a fragment that displays a modal window, floating on top of the current activity window. An instance of DialogFragment can be used to display an existing Dialog implementation dialog or a custom view hierarchy.

The Dialog class is the base class for implementing a dialog. Android provides several standard dialog implementation, AlertDialog, ProgressDialog, DatePickerDialog or TimePickerDialog. Your DialogFragment can implement the onCreateDialog method and return such a dialog implementation.

If you want to create your custom view hierarchy you can build this in the onCreateView() method of the fragment.

1.2. 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 fragment to display modal windows.. Both the re-use of an dialog implementation and a custom layout for the dialog fragment is shown.

2.1. Create project and layout files

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

Add at least two buttons to the activity layout. Both should point to the onClick method via their android:onClick property.

Create the following layout file, called fragment_username.xml.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/edit_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/lbl_your_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter user name" />

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:imeOptions="actionDone"
        android:inputType="text" />
</LinearLayout>

2.2. Create fragments and adjust activity

Create the following two fragment classes.

package com.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 {

@Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  return new AlertDialog.Builder(getActivity())
    // set dialog icon
    .setIcon(android.R.drawable.stat_notify_error)
    // 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();
     }
    }).create();
 }
}
package com.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() {}

@Override
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
  mEditText.setOnEditorActionListener(this);
  mEditText.requestFocus();
  getDialog().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  getDialog().setTitle("Please enter username");

  return view;
}

 @Override
 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
  // Return input text to activity
  UserNameListener activity = (UserNameListener) getActivity();
  activity.onFinishUserDialog(mEditText.getText().toString());
  this.dismiss();
  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 {

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

    @Override
    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) {
            manager.beginTransaction().remove(frag).commit();
        }
        switch (view.getId()) {
            case R.id.showCustomFragment:
                MyDialogFragment editNameDialog = new MyDialogFragment();
                editNameDialog.show(manager, "fragment_edit_name");
                break;
            case R.id.showAlertDialogFragment:
                MyAlertDialogFragment alertDialogFragment = new MyAlertDialogFragment();
                alertDialogFragment.show(manager, "fragment_edit_name");
                break;
        }
    }
}

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

TRAINING SERVICE & 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.