Step by step guide on how to use the new Material Date Range Picker in android
Android Material Components released a new Date Picker around October 2019 with further improvements. You can check out the UI/UX https://material.io/components/pickers/#
Recently we wanted to change the third party library we were using for Date Range Pickers. While researching many Android date range pickers I came across this one and it seemed like a good fit for our use case. I couldn’t find much documentation or how to use it so I decided to write my own tutorial.
It's quite easy to use.
Step 1: Add dependency to build.gradle (app) file
You can select the latest stable release from https://github.com/material-components/material-components-android/releases . After adding the dependency, sync the Gradle files.
( "com.google.android.material:material:1.2.0-alpha03" )
Step 2: Check App Theme
Make sure your app theme inherits the Material Components theme. If using the AppCompat theme, inherit from one of the Bridge themes as mentioned here https://github.com/material-components/material-components-android/blob/master/docs/getting started.md
[Note: If you don't do this, the app will crash when creating the picker]
<style name= "Application Theme" parent= "Theme.MaterialComponents.Light.DarkActionBar.Bridge" >
Step 3: Initialize the Material date range picker builder
In any fragment or activity you want to open the date range picker, create a builder instance there.
[Note: You can also create a datePicker instance if you want to use that]
val builder = MaterialDatePicker.Builder.dateRangePicker()
Step 4 (optional): Set various attributes for the creator.
val now = Calendar.getInstance() builder.setSelection(androidx.core.util.Pair(now.timeInMillis , now.)timeInMillis
Step 5: Create build and view
val picker = builder.build() picker.show(activity?.!!, picker.toString())supportFragmentManager
Step 6: Add logic in Listener
picker.addOnNegativeButtonClickListener { dismiss() } selector .addOnPositiveButtonClickListener { Timber.i( "The selected date range is ${it.first} - ${it.second}" )}