Android DialogFragment Example

0

In this article, we will see how to use DialogFragment to create an AlertDialog. DialogFragment class was originally added with Android 3.0 (API level 11). You may also want to read my example on AlertDialog.

Why is extending DialogFragment a better design?

  1. Since it is a Fragment the dialog can always be re-used in more than one activity
  2. DialogFragment being a Fragment itself and part of the Activity class, it automatically gets all the lifecycle events.

Steps to build AlertDialog using DialogFragment

  1. Create your own Fragment class extending DialogFragment
  2. Creating an AlertDialog in the DialogFragment.onCreateDialog() callback method.
  3. Your main activity should extend ActivityFragment class
  4. To show the dialog, you need to create an instance of DialogFragment from the main activity and call show

Main Layout

Main layout consists of a text field and a button. When the button is clicked, we want to show the alert dialog.

welcome.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.javarticles.android.AlertDialogExampleActivity" >

    <TextView
        android:id="@+id/welcome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="18dp"
        android:text="@string/welcome"
        android:textColor="@color/welcome_text_color"
        android:textSize="20sp" />

    <Button
        android:id="@+id/open_alert_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/welcome"
        android:layout_below="@+id/welcome"
        android:layout_marginLeft="48dp"
        android:layout_marginTop="30dp"
        android:text="@string/alert_dialog_btn" />

</RelativeLayout>

Create AlertDialog

Steps to create AlertDialog.

  1. Create AlertDialog in DialogFragment.onCreateDialog and return it. This will be called as a callback from the main activity class.
  2. Use an instance of AlertDialog.Builder to build the AlertDialog.
  3. Call AlertDialogBuilder.create() to create AlertDialog.

To add action buttons Ok and Cancel, call the setPositiveButton() and setNegativeButton() methods. Pass an instance of DialogInterface.OnClickListener to define the action to be performed when user presses the button.

In our example, when user presses ‘Ok’, we want to open another screen. When ‘Cancel’ is pressed, we will simply display a message.

Use neutral when you want to proceed with an action which is neither positive nor negative buttons. In our case, when the neutral button ‘Exist’ is pressed, we will finish with our activity.

AlertDialogFragmentExample:

package com.javarticles.android;


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

public class AlertDialogFragmentExample extends DialogFragment {

	@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {		
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity())
        .setTitle(R.string.alert_dialog_title)
        .setMessage(R.string.alert_dialog_message)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(getActivity(), ConfigurationActivity.class);
				startActivity(intent);
			}})
	    .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(getActivity(), "Canceled", Toast.LENGTH_SHORT).show();
				
			}})
			.setNeutralButton(R.string.exit, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getActivity().finish();
				}
			});
		
		return alertDialogBuilder.create();
	}
		
}

Main Activity

In the MainActivity, we will configure the button so that when clicked, it creates the DialogFragment and then calls show. Note that we also pass getFragmentManager() object so that the fragment gets added to the given FragmentManager.

MainActivity:

package com.javarticles.android;

import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends FragmentActivity {
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);
		Button alertBtn = (Button) findViewById(R.id.open_alert_btn);
		alertBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				DialogFragment alertDialExample = new AlertDialogFragmentExample();
				alertDialExample.show(getFragmentManager(), "AlertDialogFragment");
			}
		});
	}
}

Run the application

Alert Dialog to Configure.

alert_dialog

Alert Dialog to Configure

Click on Cancel to close the alert.

Cancel

On Cancel

Click on Ok to navigate to Configuration screen.

Ok

On Ok

Click on Exist to finish with the activity.

Neutral

Neutral Case

Download the Source Code

This was an example of AlertDialog using DialogFragment. You can download the source code here: alertDialogFragmentExample.zip

Share.

Comments are closed.