Android pick date time from EditText OnClick event


Android DatePickerDialog TimePickerDialog EditText

 

In this tutorial I would teach you how to pick date and time in Android on single event, for this case I am using the OnClick event of an EditText. Being a mobile app consultant at Truiton I have come across many situations where both date and time are taken as an input from user, and rarely there’s a case where only one of the value is required. So here goes the tutorial.

I am assuming who ever is reading this tutorial has a basic understanding of how to create an android project, therefore lets continue to next step by creating a layout for your activity.

It should look something like this :

Android Date Time Picker EditText

Now next step would be to create a class TimePickerFragment in our MainActivity which extends DialogFragment, remember we are using DatePicker and TimePicker as dialogs. Also we are maintaining backward compatibility with previous versions of android APIs – to do this we are using android support v4 libraries.

Next step would be to create a class to implement DatePickerDialog. Again I would like to remind that only import android.support.v4.app.DialogFragment package as we want to maintain backward compatibility.

Now lets create methods to call these classes

Now we have achieved the functionality to call the Android DatePicker and TimePicker Dialogs in same class, we just have to write an onCreate method to call these date and time picker dialogs at OnClick event of an EditText.

After creating onCreate method and completing the class we would get something like this

 

Although the code is self explanatory, what we are doing in this last step is just calling two methods which create date and time picker dialogs at setOnClickListener of EditText. Here first DatePickerDialog is called, its value is returned to the EditText, next TimePickerDialog is called and its value is appended to the EditText value, and Voila here we have date and time input from a single click/tap. If you like this post please like our page or share this with your friends.

About Mohit Gupt

An android enthusiast, and an iPhone user with a keen interest in development of innovative applications.


Leave a comment

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

8 thoughts on “Android pick date time from EditText OnClick event