Category

Calendar

Category

In this example, you will learn how to open the calendar on button click in Android with an example. Here I use DatePickerDialog, not CalendarView. Beginners tend to use Calendar, that’s why I use that here.



Download Source Code Now


Let’s discuss in simple steps.

1. Create a button and make it listen for events.

2. Access current date.

3. Initialize DatePickerDialog with the current date and show it. If you don’t and use 0 as day, month and year. Then DatePickerDialog shows Feb month 1900.


4. Get day, month and year from DatePickerDialog onDateSet() method.
When you select a date in DatePickerDialog, onDateSet() method gives day, year in the as correct number specified in DatePickerDialog. But month value varies from 0 to 11. So just add 1 to month value to show original month number.

Just like below.

Create Project – Open Calendar on Button click in Android Example

Let’s create a project that sets the date in EditText. When you click on Button, DatePickerDialog shows up, When you select a date, it sets on EditText.

Start a new Android Studio project

Application name: Open Calendar on Button Click in Android Example.

Company domain: androidride.example.com

check to include Kotlin support.


Select minimum SDK: API 15 – Android 4.0.3 (Ice Cream Sandwich) and click Next.

Next dialog, Select Empty Activity and click Next.

Activity Name: MainActivity
Check Generate layout file

Layout Name: activity_main

Click Finish.


Make a layout using below code

Open calendar on button click in Android Example
Open calendar on button click in Android Example

colors.xml

strings.xml

styles.xml

activity_main.xml

MainActivity.kt

open calendar on button click in android example
open calendar on button click in android example

Conclusion
There are many occasions when you need a date from the user. Date of birth in sign up process, Ticket reservation, and date of an upcoming event just like that. It may not be user-friendly If the user needs to type it down. Android provides views for that, so users can easily pick it up. So I think if you are making an app like that, this post might have helped you. If you like this tutorial, please share it.

Reference
DatePickerDialog – Android doc