Android dialog fragment

Android provides you DialogFragment class that can be used to create different types of dialog boxes (e.g. message dialog box, input dialog box, date picker, etc.). The dialog fragment created by the DialogFragment class is a dialog window that floats over its hosting activity. In this Android tip, I will show you how to create a simple message dialog box using the DialogFragment class.

Now create a new Android project. Then create a layout file called dialog_fragment.xml file. It is the layout file of the dialog fragment. In this file, there are one TextView and one Button. The TextView displays a message and the Button is clicked to close the dialog box.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
   android:orientation="vertical" >
     android:text="This is a message dialog box by DialogFragment."


Then create DlgFragment class that extends the DialogFragment class. The instance of the DlgFragment class is the dialog box that will be shown in the MainActivity activity.

  package com.example.androidproject;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class DlgFragment extends DialogFragment{

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set dialog title
getDialog().setTitle("dialog box");
//Inflate the layout for this fragment
View view=inflater.inflate(R.layout.dialog_fragment, container, false);
//create a reference to the Button
Button bt=(Button)view.findViewById(;
//add click listener to the button
bt.setOnClickListener(new OnClickListener(){
public void onClick(View view){
dismiss(); //close the dialog
return view;


To display the dialog box to the user, in the onCreate method of the MainActivity class, you will write code to create an instance of DlgFragment and invoke its show() mehtod to display the dialog box. See the example code below.

protected void onCreate(Bundle savedInstanceState) {
//create dialog instance
DlgFragment df=new DlgFragment();
//show the dialog, "df");



Posted by: Dara | post date: 07-23-2014 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.