Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaMaterial Design Date Picker in Android

Material Design Date Picker in Android

Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android applications. 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 are 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

sample image

Skeleton of Date Picker Dialog Box

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.

Skeleton of Date Picker Dialog Box

Steps by Step Implementation

Step 1: Create a New Project

Step 2: Adding material design components dependency

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.

Gradle file

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


Output UI:

Output UI

Implementation of Normal Date Picker

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
                    }
                });
    }
}


Kotlin




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;
 
 
class MainActivity : AppCompatActivity() {
    private var mPickDateButton: Button? = null
    private var mShowSelectedDateText: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        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
        val materialDateBuilder: MaterialDatePicker.Builder<*> =
            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
        val materialDatePicker = materialDateBuilder.build()
 
        // handle select date button which opens the
        // material design date picker
        mPickDateButton.setOnClickListener(
            object : OnClickListener() {
                fun onClick(v: View?) {
                    // getSupportFragmentManager() to
                    // interact with the fragments
                    // associated with the material design
                    // date picker tag is to get any error
                    // in logcat
                    materialDatePicker.show(supportFragmentManager, "MATERIAL_DATE_PICKER")
                }
            })
 
        // now handle the positive button click from the
        // material design date picker
        materialDatePicker.addOnPositiveButtonClickListener {
            // if the user clicks on the positive
            // button that is ok button update the
            // selected date
            mShowSelectedDateText.setText("Selected Date is : " + materialDatePicker.headerText)
            // in the above statement, getHeaderText
            // is the selected date preview from the
            // dialog
        }
    }
}
// This code is written by Ujjwal Kumar Bhardwaj


Output: Run on Emulator

Implementation of Date Range Picker

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
                    }
                });
    }
}


Output: Run on Emulator

To implement more functionalities of Material Design Date Picker please refer to More Functionalities of Material Design Date Picker in Android article.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments