How to create a CalendarPickerView using TimeSquare library

This article shows how to create a calendarPickerView using TimeSquare Library. We have seen the use of calendarPickerView to select a date in many applications. With the help of this library, we can easily add a calendar in our app.
Approach:
- Add the support Library in build.gradle file and add dependency in the dependencies section. This library provides the inbuilt calendar widget and various functions such as to select a particular date, etc.
dependencies {implementation 'com.squareup:android-times-square:1.6.5@aar'} - Now add the following code in the activity_main.xml file. This will add the CalendarPickerView Layout in the app.
activity_main.xml
<?xmlversion="1.0"encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><com.squareup.timessquare.CalendarPickerViewandroid:id="@+id/calendar"android:layout_width="match_parent"android:layout_height="match_parent"/></androidx.constraintlayout.widget.ConstraintLayout> - Now add the following code in the MainActivity.java file. This will show the calendar of next one year from the current day’s date. A setOnDateSelectedListener is added in the calendar which is invoked when the user clicks on any date. The function Toasts the selected day’s date on the screen.
MainActivity.java
packageorg.zambiatek.gfgcalendarPickerView;importandroidx.appcompat.app.AppCompatActivity;importandroid.os.Bundle;importandroid.widget.Toast;importcom.squareup.timessquare.CalendarPickerView;importjava.text.DateFormat;importjava.util.Calendar;importjava.util.Date;publicclassMainActivityextendsAppCompatActivity {@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// This will return us today dateDate today =newDate();Calendar nextYear= Calendar.getInstance();// This will help us// to show date from// today to next yearnextYear.add(Calendar.YEAR,1);CalendarPickerViewdatePicker= findViewById(R.id.calendar);// we have to initialize// our calendar picker view// so we select min date as today// max date as next year// we call getTime() method// because we want to// retrieve date from it.datePicker.init(today, nextYear.getTime()).inMode(CalendarPickerView.SelectionMode.RANGE).withSelectedDate(today);// when the user select// or un select any date then// this method called automatically.datePicker.setOnDateSelectedListener(newCalendarPickerView.OnDateSelectedListener() {@OverridepublicvoidonDateSelected(Date date){// we have to format our date// object that's why we are// using DateFormat class.String selectedDate= DateFormat.getDateInstance(DateFormat.FULL).format(date);Toast.makeText(MainActivity.this,selectedDate,Toast.LENGTH_SHORT).show();}@OverridepublicvoidonDateUnselected(Date date){}});}}
Output:



