-
-
Save goforbg/d7ca9699f5e6257bd92aa71aff325fdd to your computer and use it in GitHub Desktop.
A useful extension function to transform EditText into DatePicker 💡
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun TextInputEditText.transformIntoDatePicker( | |
context: Context, | |
format: String, | |
maxDate: Date? = null | |
) { | |
isFocusableInTouchMode = false | |
isClickable = true | |
isFocusable = false | |
val myCalendar = Calendar.getInstance() | |
val datePickerOnDataSetListener = | |
DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> | |
myCalendar.set(Calendar.YEAR, year) | |
myCalendar.set(Calendar.MONTH, monthOfYear) | |
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) | |
val sdf = SimpleDateFormat(format, Locale.UK) | |
setText(sdf.format(myCalendar.time)) | |
} | |
setOnClickListener { | |
DatePickerDialog( | |
context, | |
datePickerOnDataSetListener, | |
myCalendar | |
.get(Calendar.YEAR), | |
myCalendar.get(Calendar.MONTH), | |
myCalendar.get(Calendar.DAY_OF_MONTH) | |
).run { | |
maxDate?.time?.also { datePicker.maxDate = it } | |
show() | |
} | |
} | |
} | |
// Transform TextInputEditText to DatePicker using Ext function | |
editText.transformIntoDatePicker( | |
requireContext(), | |
"dd/MM/yyyy", | |
Date() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment