Skip to content

Instantly share code, notes, and snippets.

@Spikeysanju
Created January 22, 2021 06:54
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Spikeysanju/f70b9e20ca11e0e4a6acff8836e32fd9 to your computer and use it in GitHub Desktop.
Save Spikeysanju/f70b9e20ca11e0e4a6acff8836e32fd9 to your computer and use it in GitHub Desktop.
A useful extension function to transform EditText into DatePicker 💡
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