Opening a DailogFragment on an item click in Android

July 4, 2012

DialogFragment is a fragment that displays a dialog window on the top of the calling activity’s window. The objective of this article is to create an Android application which opens a dialog window when clicking on a country listed in the listview. In the opening dialog window, the local time of the selected country will be displayed. Please jump to the end of this article to view the screen shot of this application.

1. Create an Android project namely “OpenDialogFragment”

New Android Project

Figure 1: New Android Project

2. Select Android build target

Select Android Build Target

Figure 2 : Select Android Build Target

3. Enter application details

Enter Application Details

Figure 3 : Enter Application Details

4. src/in/wptrafficanalyzer/opendialogfragment/

package in.wptrafficanalyzer.opendialogfragment;

public class Country {
    static String[] name = new String[] {
        "Sri Lanka",
        "North Korea",
        "South Korea",

    static String[] tz = new String[] {

5. res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>

    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">OpenDialogFragment</string>
    <string name="str_empty">No Items Found</string>
    <string name="str_tv_current_time">Current Time</string>


6. res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >





7. res/layout/dialog_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >



8. src/in/wptrafficanalyzer/opendialogfragment/

package in.wptrafficanalyzer.opendialogfragment;

import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TimeDialogFragment extends DialogFragment{
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        /** Inflating layout for the dialog */
        View v = inflater.inflate(R.layout.dialog_layout, null);

        /** Getting the arguments passed to this fragment. Here we expects the selected item's position as argument */
        Bundle b = getArguments();

        /** Setting the title for the dialog window */
        getDialog().setTitle("Time @ " +[b.getInt("position")] );

        /** Getting the reference to the TextView object of the layout */
        TextView tv = (TextView) v.findViewById(;

        /** Setting the current time to the TextView object of the layout */

        /** Returns the View object */
        return v;

    * @param position .The position of the selected list item
    * @return. Returns the current time corresponding to the selected country
    public String getCurTime(int position){
        String curTime = "";

        /** Creating TimeZone object corresponding to the selected country */
        TimeZone timezone = TimeZone.getTimeZone([position]);

        /** Creating a DateFormat object */
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT);

        /** Setting the TimeZone for the DateFormat object */

        /** Getting the current date */
        Date d = new Date();

        /** Formatting the current date with DateFormat object */
        curTime = df.format(d);

        /** Returns the formatted date corresponds to the selected country */
        return curTime;

9. src/in/wptrafficanalyzer/opendialogfragment/

package in.wptrafficanalyzer.opendialogfragment;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        /** Array adapter to store a list of countries, which acts as a datasource to the list */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,;

        /** Setting the data source to the list view */

        /** An Item click listener , will be invoked when an item in the list view is clicked */
        OnItemClickListener listener = new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {

                /** Instantiating TimeDailogFragment, which is a DialogFragment object */
                TimeDialogFragment tFragment = new TimeDialogFragment();

                /** Creating a bundle object to store the position of the selected country */
                Bundle b = new Bundle();

                /** Storing the position in the bundle object */
                b.putInt("position", position);

                /** Setting the bundle object as an argument to the DialogFragment object */

                /** Getting FragmentManager object */
                FragmentManager fragmentManager = getFragmentManager();

                /** Starting a FragmentTransaction */
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                /** Getting the previously created fragment object from the fragment manager */
                TimeDialogFragment tPrev =  ( TimeDialogFragment ) fragmentManager.findFragmentByTag("time_dialog");

                /** If the previously created fragment object still exists, then that has to be removed */

                /** Opening the fragment object */
          , "time_dialog");

        /** Setting an item click event handler for the list view */


10. Application Screenshot

Displaying current time in a dialog window

Figure 4 : Displaying current time of the selected country in a dialog window


12. Reference

How to hire me?

I am George Mathew, working as software architect and Android app developer at

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to

My other blogs

Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :

Tags: , , , , ,

4 Responses to Opening a DailogFragment on an item click in Android

  1. Sumit on January 29, 2013 at 5:58 pm

    Sample is great.

    One question what is “time_dialog”, i searched in whole project and could not find it.

  2. Ron on February 12, 2014 at 9:37 am

    hi. Dear I read your blog and looked everywhere. Please your help
    I’m trying to generate the following sequence of calls FragmentActivity -> DialogFragment1 -> DialogFragment2. Wherein the selected data DialogFragment2 need you in FramentActivity.
    All good until the first DialogFragment1, but after I started to send error with the listener: dlgResult = (DialogListener) getActivity ();

    I hope I have explained the problem. It’s a get data from a flame of a dialog from another dialog.

  3. Richard on November 11, 2014 at 2:24 am

    Hey, so I downloaded your code and I wanted to see it run. However, I keep getting R cannot be resolved to a variable. How do I fix this? Please help

  4. Milind Chothe on January 5, 2016 at 12:00 pm

    Hello Sir,
    I am a student and wants to learn.
    I wants to launch fragment in new separated window by clicking on the button in Main Activity. Main Activity has 1 Button and 1 list_view only. List_view primarily should be empty.
    The fragment has 3 edit_text fields for product_id, product_name and product_price and 1 save button.
    The entered fields should saved in SQLite database and the only product_name and product_price are displayed in list_view available on Main Activity.
    (My problem is I get fragment window under the Main_Activity’s button and list_view is not showing. I get only single window. When I click the button on Main_Activity the new fragment is created below to the my edit_text fields (fragment fields) so that I get two unnecessary fragments I want only single window and that should open in new window not to below of that Main_Activity window )
    Will you please help me ? Awaiting for your valuable reply.
    Thanks & Regards,
    Milind Chothe

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner