Material Design Date Picker in Android

23 Oct, 2020
Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Design Components (MDC) Date Picker. There are a lot of date pickers available for Android which are Open Source. But the Material design date pickers offer more functionality to the user and easy to implement for developers. Have a look at the following images on what type of material design date pickers are going to be discussed in this discussion. Note that we are going to implement this project using the Java language. In this article, we are going to implement two types of material design date pickers as one can see in the below images.
Material Design Normal Date Picker
Material Design Date Range Picker
Before going to implement the material design date picker, understanding the parts of the dialog box is necessary so that it can become easier while dealing with parts of the dialog box in java code.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Note that select Java as the programming language.
Step 2: Adding material design components dependency
Now add the following dependency to the app-level gradle file.
implementation ‘com.google.android.material:material:1.3.0-alpha02’ 
After invoking the dependency click on the “Sync Now” button. Make sure you are connected to the network so that Android Studio downloads all the required files.
Refer to the following image if unable to locate the app-level gradle file and invoke the dependency.
Step 3: Change the base application theme as Material Theme as following
Go to app > src > main > res > values > styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles. Below is the code for the styles.xml file. As we are using material design components this step is mandatory.
XML
<resources>          <!-- Base application theme. -->    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">          <!-- Customize your theme here -->        <item name="colorPrimary">@color/colorPrimary</item>          <item name="colorPrimaryDark">@color/colorPrimaryDark</item>          <item name="colorAccent">@color/colorAccent</item>      </style>    </resources>
Refer to the following if unable to locate styles.xml and change the base theme of the application.
Step 4: Working with the activity_main.xml file
Invoke the following code for the application interface or can design it according to one’s needs.
And this is going to remain the same for the entire discussion. Below is the code for the activity_main.xml file. 
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity"    tools:ignore="HardcodedText">      <!--make sure to give the appropriate IDs to textView        and the button to handle them in MainActivity.java-->      <!--simple text view to show the selected date by the user-->    <TextView        android:id="@+id/show_selected_date"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_marginTop="128dp"        android:text="Selected Date is : "        android:textSize="18sp" />      <!--button to open the material design date picker dialog-->    <Button        android:id="@+id/pick_date_button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_marginTop="32dp"        android:text="Select Date"        android:textSize="18sp"        app:icon="@drawable/ic_baseline_add_to_photos_24" />  </LinearLayout>
The icon has been added to the Select Date button above in the code. However, that is optional. Refer Theming Material Design buttons in android with examples on how to add the icon to a button or how to change the theme of the button.
Output UI:
Step 5: Now invoke the following code to implement the first type of the material design date picker
Go to the MainActivity.java file, and refer to the following code. Below is the code for the MainActivity.java file. 
Comments are added inside the code to understand the code in more detail.
Java
import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import com.google.android.material.datepicker.MaterialDatePicker;import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener;  public class MainActivity extends AppCompatActivity {      private Button mPickDateButton;      private TextView mShowSelectedDateText;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // now register the text view and the button with        // their appropriate IDs        mPickDateButton = findViewById(R.id.pick_date_button);        mShowSelectedDateText = findViewById(R.id.show_selected_date);          // now create instance of the material date picker        // builder make sure to add the "datePicker" which        // is normal material date picker which is the first        // type of the date picker in material design date        // picker        MaterialDatePicker.Builder materialDateBuilder = MaterialDatePicker.Builder.datePicker();          // now define the properties of the        // materialDateBuilder that is title text as SELECT A DATE        materialDateBuilder.setTitleText("SELECT A DATE");          // now create the instance of the material date        // picker        final MaterialDatePicker materialDatePicker = materialDateBuilder.build();          // handle select date button which opens the        // material design date picker        mPickDateButton.setOnClickListener(                new View.OnClickListener() {                    @Override                    public void onClick(View v) {                        // getSupportFragmentManager() to                        // interact with the fragments                        // associated with the material design                        // date picker tag is to get any error                        // in logcat                        materialDatePicker.show(getSupportFragmentManager(), "MATERIAL_DATE_PICKER");                    }                });          // now handle the positive button click from the        // material design date picker        materialDatePicker.addOnPositiveButtonClickListener(                new MaterialPickerOnPositiveButtonClickListener() {                    @SuppressLint("SetTextI18n")                    @Override                    public void onPositiveButtonClick(Object selection) {                          // if the user clicks on the positive                        // button that is ok button update the                        // selected date                        mShowSelectedDateText.setText("Selected Date is : " + materialDatePicker.getHeaderText());                        // in the above statement, getHeaderText                        // is the selected date preview from the                        // dialog                    }                });    }}
Step 6: Now invoke the following code to implement the second type of the material design date picker
In material design date picker there is one more type of the date picker is available, that is called as date range picker.
The following code is the implementation of the date range picker.
Go to the MainActivity.java file, and refer to the following code. Below is the code for the MainActivity.java file. 
Comments are added inside the code to understand the code in more detail.
Java
import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import androidx.core.util.Pair;import com.google.android.material.datepicker.MaterialDatePicker;import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener;  public class MainActivity extends AppCompatActivity {      private Button mPickDateButton;    private TextView mShowSelectedDateText;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // now register the text view and the button with        // their appropriate IDs        mPickDateButton = findViewById(R.id.pick_date_button);        mShowSelectedDateText = findViewById(R.id.show_selected_date);          // now create instance of the material date picker        // builder make sure to add the "dateRangePicker"        // which is material date range picker which is the        // second type of the date picker in material design        // date picker we need to pass the pair of Long        // Long, because the start date and end date is        // store as "Long" type value        MaterialDatePicker.Builder<Pair<Long, Long>> materialDateBuilder = MaterialDatePicker.Builder.dateRangePicker();          // now define the properties of the        // materialDateBuilder        materialDateBuilder.setTitleText("SELECT A DATE");          // now create the instance of the material date        // picker        final MaterialDatePicker materialDatePicker = materialDateBuilder.build();          // handle select date button which opens the        // material design date picker        mPickDateButton.setOnClickListener(                new View.OnClickListener() {                    @Override                    public void onClick(View v) {                        // getSupportFragmentManager() to                        // interact with the fragments                        // associated with the material design                        // date picker tag is to get any error                        // in logcat                        materialDatePicker.show(getSupportFragmentManager(), "MATERIAL_DATE_PICKER");                    }                });          // now handle the positive button click from the        // material design date picker        materialDatePicker.addOnPositiveButtonClickListener(                new MaterialPickerOnPositiveButtonClickListener() {                    @SuppressLint("SetTextI18n")                    @Override                    public void onPositiveButtonClick(Object selection) {                          // if the user clicks on the positive                        // button that is ok button update the                        // selected date                        mShowSelectedDateText.setText("Selected Date is : " + materialDatePicker.getHeaderText());                        // in the above statement, getHeaderText                        // will return selected date preview from the                        // dialog                    }                });    }}
To implement more functionalities of Material Design Date Paicke please refer to More Functionalities of Material Design Date Picker in Android article.
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.