{"id":414,"date":"2019-10-06T17:32:57","date_gmt":"2019-10-06T07:32:57","guid":{"rendered":"https:\/\/learntodroid.com\/?p=414"},"modified":"2021-01-13T09:44:57","modified_gmt":"2021-01-12T23:44:57","slug":"how-to-disable-dates-in-a-datepicker-for-android","status":"publish","type":"post","link":"http:\/\/10.0.0.14:32769\/how-to-disable-dates-in-a-datepicker-for-android\/","title":{"rendered":"How to Disable Dates in a DatePicker for Android"},"content":{"rendered":"\n
When I have built Android apps in the past I have run into situations where I need to capture a date within the app from the user, like for example capturing the date for a customer’s appointment. Entering a date into a simple EditText field is not a great user experience so Android have created a DatePicker widget<\/a> that will present the user with a much nicer calendar display to cycle through the months and years and select a particular date from a given month.<\/p>\n\n\n\n When getting the user to capture a date, you may want to restrict what dates in that calendar that they can select. Like if you want to capture a customer’s appointment date, they won’t be booking an appointment for a date that is already in the past. Rather than have the user select the date then validating the date and presenting the user with an error message if the date is not allowed to be chosen, what if there is a better way to disable dates such as dates in the past from being selected?<\/p>\n\n\n\n The Android DatePicker allows you to prevent dates in the past from being selected by using the setMinDate(long minDate)<\/a> method. To disable dates in the past from being selected, follow the 2 steps below.<\/strong><\/p>\n\n\n\n I have created a code sample below, which is also accessible on GitHub<\/a>, showing how to set a minimum date in the Android DatePicker<\/a>, where all dates before this minimum date will be disabled.<\/p>\n\n\n\n In addition to this, I have also researched how you could achieve the following with a DatePicker:<\/p>\n\n\n\n Let’s dive in!<\/p>\n\n\n\n By setting a minimum selectable date on your DatePicker using the setMinDate(…) method, the dates before that will become greyed out and not selectable in the Calendar.<\/p>\n\n\n\n You can view this entire source code for this example in the DatePicker project<\/a> on the LearnToDroid GitHub account<\/a>.<\/p>\n\n\n\n The layout for this example is a LinearLayout with a vertical orientation that includes:<\/p>\n\n\n\nSetting a Minimum Selectable Date in the Android DatePicker<\/h2>\n\n\n\n
Create the Layout Resource<\/h3>\n\n\n\n