Material Design Date/Time Picker for Android 4.0

    I also had a post about Date/Time picker in Android Basic Course. By it, you can see that the Material design Date picker Dialog is not available in pre-lollipop devices.
    Now, I would like to present to readers an external library which can help you build a Material Design Date/Time picker Dialog from Android 4.0 (97.4% running devices now). Let's start!
    DEMO VIDEO:

Importing library

    In order to use it, please add dependency to your app/build.gralde:
dependencies {
  compile 'com.wdullaer:materialdatetimepicker:2.3.0'
}
    Because this library supports for Android 4.0 and up, so min-sdk of your project is 14.

Show Date/Time Picker Dialog

    By setup a Calendar instance to build date/time for TimePickerDialog or DatePickerDialog. For example, build and config a Date Picker Dialog simple like this:
        Calendar now = Calendar.getInstance();
        DatePickerDialog datepickerdialog = DatePickerDialog.newInstance(
                MainActivity.this,
                now.get(Calendar.YEAR),
                now.get(Calendar.MONTH),
                now.get(Calendar.DAY_OF_MONTH)
        );
        datepickerdialog.setThemeDark(true); //set dark them for dialog?
        datepickerdialog.vibrate(true); //vibrate on choosing date?
        datepickerdialog.dismissOnPause(true); //dismiss dialog when onPause() called?
        datepickerdialog.showYearPickerFirst(false); //choose year first?
        datepickerdialog.setAccentColor(Color.parseColor("#9C27A0")); // custom accent color
        datepickerdialog.setTitle("Please select a date"); //dialog title
        datepickerdialog.show(getFragmentManager(), "Datepickerdialog"); //show dialog
This dialog look like this:

    Absolutely similarity, building a Time Picker Dialog:
                Calendar now = Calendar.getInstance();
                TimePickerDialog timepickerdialog = TimePickerDialog.newInstance(MainActivity.this,
                        now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), true);
                timepickerdialog.setThemeDark(false); //Dark Theme?
                timepickerdialog.vibrate(false); //vibrate on choosing time?
                timepickerdialog.dismissOnPause(false); //dismiss the dialog onPause() called?
                timepickerdialog.enableSeconds(true); //show seconds?

                //Handling cancel event
                timepickerdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        Toast.makeText(MainActivity.this, "Cancel choosing time", Toast.LENGTH_SHORT).show();
                    }
                });
                timepickerdialog.show(getFragmentManager(), "Timepickerdialog"); //show time picker dialog
    And we'll have this dialog:

Full project code

    Your Activity must implement OnDateSetListener or OnTimeSetListener and overriding onDateSet() or onTimeSet() respectively. In these methods, we can show chosen date/time to TextView.
    Full code for the main activity:
MainActivity.java
package info.devexchanges.materialdesigndtpick;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener,
        DatePickerDialog.OnDateSetListener {

    private View btnPickDate;
    private View btnPickTime;
    private TextView textView;

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

        textView = (TextView) findViewById(R.id.text);
        btnPickDate = findViewById(R.id.btn_date);
        btnPickTime = findViewById(R.id.btn_time);

        btnPickDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar now = Calendar.getInstance();
                DatePickerDialog datepickerdialog = DatePickerDialog.newInstance(
                        MainActivity.this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );
                datepickerdialog.setThemeDark(true); //set dark them for dialog?
                datepickerdialog.vibrate(true); //vibrate on choosing date?
                datepickerdialog.dismissOnPause(true); //dismiss dialog when onPause() called?
                datepickerdialog.showYearPickerFirst(false); //choose year first?
                datepickerdialog.setAccentColor(Color.parseColor("#9C27A0")); // custom accent color
                datepickerdialog.setTitle("Please select a date"); //dialog title
                datepickerdialog.show(getFragmentManager(), "Datepickerdialog"); //show dialog
            }
        });

        btnPickTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar now = Calendar.getInstance();
                TimePickerDialog timepickerdialog = TimePickerDialog.newInstance(MainActivity.this,
                        now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), true);
                timepickerdialog.setThemeDark(false); //Dark Theme?
                timepickerdialog.vibrate(false); //vibrate on choosing time?
                timepickerdialog.dismissOnPause(false); //dismiss the dialog onPause() called?
                timepickerdialog.enableSeconds(true); //show seconds?

                //Handling cancel event
                timepickerdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        Toast.makeText(MainActivity.this, "Cancel choosing time", Toast.LENGTH_SHORT).show();
                    }
                });
                timepickerdialog.show(getFragmentManager(), "Timepickerdialog"); //show time picker dialog
            }
        });
    }

    @Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
        String hourString = hourOfDay < 10 ? "0" + hourOfDay : "" + hourOfDay;
        String minuteString = minute < 10 ? "0" + minute : "" + minute;
        String secondString = second < 10 ? "0" + second : "" + second;
        String time = "You picked the following time: " + hourString + "h" + minuteString + "m" + secondString + "s";
        textView.setText(time);
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        String date = "You picked the following date: " + dayOfMonth + "/" + (++monthOfYear) + "/" + year;
        textView.setText(date);
    }
}
    And it's layout:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="info.devexchanges.materialdesigndtpick.MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Please choose Date or Time"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text"
        android:text="Show Date Picker" />

    <Button
        android:id="@+id/btn_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_date"
        android:text="Show Time Picker" />

</RelativeLayout>
    After choosing a date from dialog, it's will be displayed by the TextView:
     In the activity code, I gave a "listener" for cancel choosing time event from user, so when click Cancel button in time picker dialog, app will show a Toast:

Conclusions and References

    For more details, you can go to this library page on @Github to read it's official doc, through that, you can find out more custom features for the picker dialog. Material design is cool, so we also would like to bring it to pre-lollipop devices, libraries like this are very helpful with making this fantastic UI style. When building an application, you should choose a theme for it carefully. Finally, thanks for reading!
Android Basic Training Course: Date/Time Picker

Android Basic Training Course: Date/Time Picker

     In the Google official document, the Date Picker widget was defined:
Android Date Picker allows you to select the date consisting of day, month and year in your custom user interface. For this functionality android provides DatePicker and DatePickerDialog components.
    Through this post, as a part of Android Basic Course series, we are going to demonstrate the use of Date/Time Picker through DialogFragment and DatePickerDialog.

Project description

    I am going to use DialogFragment (available from API 11) to host the Date Picker. DialogFragment manages the life cycle and allows different layout configurations for the DatePicker. To show a Date picker dialog, we need to define a fragment class (named DatePickerFragment) which extends the DialogFragment class and returns a DatePickerDialog from its onCreateDialog() method. And similarity,  TimePickerFragment will be used to choose time from DatePickerDialog.

Creating the Date/Time Picker DialogFragment

    As the description above, we must create a subclass of DialogFragment, use a Calendar instance in onCreateDialog():
DatePickerFragment.java
package info.devexchanges.datetimepicker;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;

import java.util.Calendar;

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        TextView tv1 = (TextView) getActivity().findViewById(R.id.textview1);
        tv1.setText("Year: " + view.getYear() + " Month: " + view.getMonth() + " Day: " + view.getDayOfMonth());
    }
}
Change Calendar properties to Calendar.HOUR_OF_DAY, Calendar.MINUTE, we'll have the time picker fragment:
TimePickerFragment.java
package info.devexchanges.datetimepicker;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    @SuppressLint("SetTextI18n")
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
        TextView tv1 = (TextView) getActivity().findViewById(R.id.textview1);
        if (Build.VERSION.SDK_INT >= 23)
            tv1.setText("Hour: " + view.getHour() + " Minute: " + view.getMinute());
        else
            tv1.setText("Hour: " + view.getCurrentHour() + " Minute: " + view.getCurrentMinute());

    }
}

Creating the main activity

    As you can see at the fragments code, onDateSet() called when user complete choose the date/time, the data (year/month/day) will be shown to a TextView in an activity. So, make a main activity layout simple like this:
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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:onClick="showDatePickerDialog"
        android:text="@string/pick_date" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/btn1"
        android:onClick="showTimePickerDialog"
        android:text="Pick Time" />

</RelativeLayout>
    And it's programmatically code:
MainActivity.java
package info.devexchanges.datetimepicker;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public void showTimePickerDialog(View view) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getSupportFragmentManager(), "timePicker");
    }
}
    Running application, in Lollipop devices and later, we'll have this output (in Material design style):
And in KitKat device:
After pick date/time, it will show in the TextView:

Conclusions

    Now, you've learned how to dealing with date/time input, this is not quite hard topic in Android development. More details, let go to the official guide page of Android developer to deep understanding it. Thanks for reading and please subscribe my blog to get newest tutorials!