Android DatePicker Using Kotlin With Example

In this article, we will learn about android DatePicker using Kotlin. We will go through various example that demonstrates how to use different attributes of DatePicker. For example,

In this article, we will get answer to questions like –

  • What is DatePicker?
  • Why should we consider DatePicker while designing ui for any app?
  • What are possibilities using DatePicker while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin DatePicker Output Android DatePicker Using Kotlin

Tutorialwing Kotlin DatePicker Output

Getting Started

We can define android DatePicker widget as below –

DatePicker is a widget that display view to select any date.

Now, how do we use DatePicker in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as DatePicker. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android DatePicker Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using DatePicker in Kotlin

Follow steps below to use DatePicker in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">DatePicker</string>
    </resources>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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"
        tools:context=".MainActivity">
    
        <DatePicker
            android:id="@+id/datePicker"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="40dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="40dp"
            android:visibility="gone"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/datePicker" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    In activity_main.xml file, we have defined textView and datePicker widgets. Now, we will access these widgets in kotlin file to perform some operations on it.

  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.datepicker
    
    import android.os.Bundle
    import android.view.View
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.datepicker.databinding.ActivityMainBinding
    import java.util.*
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupDatePicker()
    	}
    
    	private fun setupDatePicker() {
    		val today = Calendar.getInstance()
    		binding.datePicker.init(
    			today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH)
    
    		) { view, year, monthOfYear, dayOfMonth ->
    			val month = monthOfYear + 1
    			val msg = "Selected Date is $dayOfMonth/$month/$year"
    			Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
    
    			binding.textView.text = msg
    			binding.textView.visibility = View.VISIBLE
    		}
    	}
    }
    

    We have accessed textView and datePicker using kotlin file (i.e. MainActivity.kt file) in the application. Then, we have set a listener to show selected date in the textView.

Now, run the application. We will get output as below –

Tutorialwing Kotlin DatePicker Output Android DatePicker Using Kotlin

Tutorialwing Kotlin DatePicker Output

Different Attributes of DatePicker in XML

Now, we will see how to use different attributes of Android DatePicker using Kotlin to customise it –

Set Id of DatePicker

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of DatePicker using android:id attribute like below –

    <DatePicker
        android:id="@+id/datePicker_ID"
        />

Here, we have set id of DatePicker as datePicker_ID using android:id=”” attribute. So, if we need to reference this DatePicker, we need to use this id – datePicker_ID.
Learn to Set ID of DatePicker Dynamically

Set Width of DatePicker

We use android:layout_width=”” attribute to set width of DatePicker.
We can do it as below –

    <DatePicker
        android:id="@+id/datePicker_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of DatePicker Dynamically

Set Height of DatePicker

We use android:layout_height=”” attribute to set height of DatePicker.
We can do it as below –

    <DatePicker
        android:id="@+id/datePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of DatePicker Dynamically

Set Padding of DatePicker

We use android:padding=”” attribute to set padding of DatePicker.
We can do it as below –

    <DatePicker
        android:id="@+id/datePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in DatePicker using android:padding=”” attribute.
Learn to Set Padding of DatePicker Dynamically

Set Margin of DatePicker

We use android:layout_margin=”” attribute to set margin of DatePicker.
We can do it as below –

    <DatePicker
        android:id="@+id/datePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in DatePicker using android:layout_margin=”” attribute.
Learn to Set Margin of DatePicker Dynamically

Set Background of DatePicker

We use android:background=”” attribute to set background of DatePicker.
We can do it as below –

    <DatePicker
        android:id="@+id/datePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in DatePicker using android:background=”” attribute.
Learn to Set Background of DatePicker Dynamically

Set Visibility of DatePicker

We use android:visibility=”” attribute to set visibility of DatePicker.
We can do it as below –

    <DatePicker
        android:id="@+id/datePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of DatePicker using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of DatePicker Dynamically

Till now, we have see how to use android DatePicker using Kotlin. We have also gone through different attributes of DatePicker to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android DatePicker Widget

Below are the various attributes that are used to customise android DatePicker Widget. However, you can check the complete list of attributes of DatePicker in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of android datePicker widget are –

Sr. XML Attributes Description
1 android:calendarTextColor Specifies text color of the calendar
2 android:calendarViewShown Checks whether calendar view is shown or not
3 android:datePickerMode Specifies the look of the widget
4 android:dayOfWeekBackground Specifies the background color for the header’s day of week
5 android:endYear Specifies the last year (inclusive) of the calendar
6 android:firstDayOfWeek Specifies the first day of the week according to Calendar
7 android:headerBackground Specifies background for the selected date header
8 android:maxDate Specifies the maximal date shown by the calendar in mm/dd/yyyy format
9 android:minDate Specifies the minimal date shown by the calendar in mm/dd/yyyy format
10 android:spinnersShown Specifies whether spinners are shown or not
11 android:startYear Specifies the first year (inclusive) of the calendar

Some of the popular attributes of DatePicker inherited from FrameLayout are –

Sr. XML Attributes Description
1 android:foregroundGravity Specifies the gravity of the foreground drawable
2 android:measureAllChildren When measuring, It specifies whether to measure all children or only those that are in visible or invisible state

Some of the popular attributes of android datePicker inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:animationCache Specifies whether layout animations should create a drawing cache for their children
2 android:layoutAnimation Specifies the layout animation to use the first time the ViewGroup is laid out
3 android:layoutMode Specifies the layout mode

Some of the popular attributes of datePicker inherited from View are –

Sr. XML Attributes Description
1 android:fadeScrollbars Specifies whether scrollbar should fade out when not in use or not
2 android:fitsSystemWindows Specifies whether to adjust view layout according to system windows
3 android:id Specifies id of the view
4 android:minHeight Specifies minimum height
5 android:minWidth Specifies minimum width
6 android:padding Specifies padding of the view
7 android:visibility Specifies visibility of the view

We have seen different attributes of DatePicker and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is DatePicker, how can we use android DatePicker using Kotlin ? etc. We also went through different attributes of android DatePicker.