Opening a DailogFragment on an item click in Android

July 4, 2012
By

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/Country.java


package in.wptrafficanalyzer.opendialogfragment;

public class Country {
    static String[] name = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan"
    };

    static String[] tz = new String[] {
        "GMT+5:30",
        "GMT+5:00",
        "GMT+5:30",
        "GMT+8:00",
        "GMT+6:00",
        "GMT+5:45",
        "GMT+4:30",
        "GMT+9:00",
        "GMT+9:00",
        "GMT+9:00"
    };
}


5. res/values/strings.xml


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

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

</resources>


6. res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

    />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_empty"
        android:layout_gravity="center_horizontal"
    />

</LinearLayout>


7. res/layout/dialog_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_current_time"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_tv_current_time"
        android:padding="30dp"
    />

</LinearLayout>


8. src/in/wptrafficanalyzer/opendialogfragment/TimeDialogFragment.java


package in.wptrafficanalyzer.opendialogfragment;

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

import android.app.DialogFragment;
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{
    @Override
    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 @ " + Country.name[b.getInt("position")] );

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

        /** Setting the current time to the TextView object of the layout */
        tv.setText(getCurTime(b.getInt("position")));

        /** 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(Country.tz[position]);

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

        /** Setting the TimeZone for the DateFormat object */
        df.setTimeZone(timezone);

        /** 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/MainActivity.java


package in.wptrafficanalyzer.opendialogfragment;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListActivity;
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. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** 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, Country.name);

        /** Setting the data source to the list view */
        setListAdapter(adapter);

        /** An Item click listener , will be invoked when an item in the list view is clicked */
        OnItemClickListener listener = new OnItemClickListener() {
            @Override
            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 */
                tFragment.setArguments(b);

                /** 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 */
                if(tPrev!=null)
                    fragmentTransaction.remove(tPrev);

                /** Opening the fragment object */
                    tFragment.show(fragmentTransaction, "time_dialog");
            }
        };

        /** Setting an item click event handler for the list view */
        getListView().setOnItemClickListener(listener);

    }
}


10. Application Screenshot

Displaying current time in a dialog window

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


11. Downloads


12. Reference

http://developer.android.com/guide/index.html


How to hire me?

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

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

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


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