Support free tutorials



vogella training Training Books

Showing dialogs in Android with fragments - Tutorial

Lars Vogel

Version 10.0

20.07.2015

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 dialogs. 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 dialogs, 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 also here 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 for this purpose 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.

The 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.3. 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 {
    @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 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() {

    }

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

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.4. Test dialog usage

If you run your application and click the corresponding button, your dialogs are 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

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.