Disable DatePicker changing year by scrolling months

Issue

I have a DatePicker and the issue I’m encountering is that going from december to january is possible, but I want to only display 12 values for the months, from January to December, without the possibility to change year from the month part of the datepicker.

1

You can see on the above image what I’m talking about if I’m not clear enough. Here I can go from janv. (january) to december, and the year will change to 2021. How can I disable this functionality ? Thank you in advance!

Here’s how I define my DatePicker :

<DatePicker
    android:id="@+id/date_input"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:calendarViewShown="false"
    android:datePickerMode="spinner"/>

Solution

I have developed below logic to stop auto scroll year when we jump from January to December or December to January

val savedMonthOfYear = 0
val savedYear = 0

date_input.setOnDateChangedListener { view, year, monthOfYear, dayOfMonth ->
            if ((savedMonthOfYear == 0 && monthOfYear == 11) || (savedMonthOfYear == 11 && monthOfYear == 0)) {
                if (savedYear != year) {
                    date_input.updateDate(savedYear, monthOfYear, dayOfMonth)
                }
            } else {
                savedYear = year
            }
            savedMonthOfYear = monthOfYear
        }

Answered By – Jaydeep parmar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published