Displaying TimePickerDialog using DialogFragment in Android with backward compatibilty support library

August 16, 2012
By

In this article we will create an Android application which demonstrate how to display a timepicker widget using dialog fragment. Since DialogFragment is introduced beginning with Android 3.0 ( API level 11 ) , we will make use Android support library to work this application in Android 1.6 ( API level 4 ) and its higher versions.

In this application, the set time is sent from TimePickerDialog to MainActivity using Handler object.

This application is developed using Eclipse IDE ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3)


1. Create new Android application project namely “TimePickerDialogDemo”

New Andriod Application Project

Figure 1 : New Andriod Application Project


2. Design application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity

Create a blank Activity

Figure 3 : Create a blank Activity


4. Enter MainActivity Details

Enter Main Activity Details

Figure 4 : Enter Main Activity Details


5. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project ( “DatePickerDialogDemo”)
  • Then from popup window, Click “Android Tools -> Add Support Library “

6. Update the file res/values/strings.xml

<resources>

    <string name="app_name">TimePickerDialogDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">TimePickerDialogDemo</string>
    <string name="str_btn_label">Set Time !!!</string>

</resources>

7. Update the layout file res/layout/activity_main.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" >

    <Button
        android:id="@+id/btnSet"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_label"
    />
</RelativeLayout>


8. Create a fragment class TimePickerDialogFragment in the file src/in/wptrafficanalyzer/timepickerdialogdemo/TimePickerDialogFragment.java


package in.wptrafficanalyzer.timepickerdialogdemo;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.widget.TimePicker;

public class TimePickerDialogFragment extends DialogFragment {
    Handler mHandler ;
    int mHour;
    int mMinute;

    public TimePickerDialogFragment(Handler h){
        /** Getting the reference to the message handler instantiated in MainActivity class */
        mHandler = h;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){

        /** Creating a bundle object to pass currently set time to the fragment */
        Bundle b = getArguments();

        /** Getting the hour of day from bundle */
        mHour = b.getInt("set_hour");

        /** Getting the minute of hour from bundle */
        mMinute = b.getInt("set_minute");

        TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                mHour = hourOfDay;
                mMinute = minute;

                /** Creating a bundle object to pass currently set time to the fragment */
                Bundle b = new Bundle();

                /** Adding currently set hour to bundle object */
                b.putInt("set_hour", mHour);

                /** Adding currently set minute to bundle object */
                b.putInt("set_minute", mMinute);

                /** Adding Current time in a string to bundle object */
                b.putString("set_time", "Set Time : " + Integer.toString(mHour) + " : " + Integer.toString(mMinute));

                /** Creating an instance of Message */
                Message m = new Message();

                /** Setting bundle object on the message object m */
                m.setData(b);

                /** Message m is sending using the message handler instantiated in MainActivity class */
                mHandler.sendMessage(m);
            }
        };

        /** Opening the TimePickerDialog window */
        return new TimePickerDialog(getActivity(), listener, mHour, mMinute, false);
    }
}


9. Update the class MainActivity in the file src/in/wptrafficanalyzer/timepickerdialogdemo/MainActivity.java


package in.wptrafficanalyzer.timepickerdialogdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

    int mHour = 15;
    int mMinute = 15;

    /** This handles the message send from TimePickerDialogFragment on setting Time */
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message m){
            /** Creating a bundle object to pass currently set Time to the fragment */
            Bundle b = m.getData();

            /** Getting the Hour of day from bundle */
            mHour = b.getInt("set_hour");

            /** Getting the Minute of the hour from bundle */
            mMinute = b.getInt("set_minute");

            /** Displaying a short time message containing time set by Time picker dialog fragment */
            Toast.makeText(getBaseContext(), b.getString("set_time"), Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Click Event Handler for button */
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {

                /** Creating a bundle object to pass currently set time to the fragment */
                Bundle b = new Bundle();

                /** Adding currently set hour to bundle object */
                b.putInt("set_hour", mHour);

                /** Adding currently set minute to bundle object */
                b.putInt("set_minute", mMinute);

                /** Instantiating TimePickerDialogFragment */
                TimePickerDialogFragment timePicker = new TimePickerDialogFragment(mHandler);

                /** Setting the bundle object on timepicker fragment */
                timePicker.setArguments(b);

                /** Getting fragment manger for this activity */
                FragmentManager fm = getSupportFragmentManager();

                /** Starting a fragment transaction */
                FragmentTransaction ft = fm.beginTransaction();

                /** Adding the fragment object to the fragment transaction */
                ft.add(timePicker, "time_picker");

                /** Opening the TimePicker fragment */
                ft.commit();
            }
        };

        /** Getting an instance of Set button */
        Button btnSet = (Button)findViewById(R.id.btnSet);

        /** Setting click event listener for the button */
        btnSet.setOnClickListener(listener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


10. Screenshot of the application in execution

Time Picker Dialog in execution

Figure 5 : Time Picker Dialog in execution


11. Download


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

One Response to Displaying TimePickerDialog using DialogFragment in Android with backward compatibilty support library

  1. Lahiru on March 27, 2013 at 4:58 pm

    Thanks .

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