Created
January 22, 2021 06:54
-
-
Save Spikeysanju/f70b9e20ca11e0e4a6acff8836e32fd9 to your computer and use it in GitHub Desktop.
A useful extension function to transform EditText into DatePicker π‘
This file contains hidden or 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