Skip to content

Instantly share code, notes, and snippets.

@leinardi
Created May 29, 2018 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leinardi/0c5bec371b74b8d1fcab339c03192cab to your computer and use it in GitHub Desktop.
Save leinardi/0c5bec371b74b8d1fcab339c03192cab to your computer and use it in GitHub Desktop.
import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
private const val INITIAL_MONTH_ADD_ON = "0"
private const val DEFAULT_MONTH = "01"
private const val SEPARATOR = "/"
class TwoDigitMonthYearInputTextWatcher(val editText: EditText) : TextWatcher {
private var length: Int = 0
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// No-op
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
length = editText.text.length
}
@SuppressLint("SetTextI18n")
override fun afterTextChanged(s: Editable) {
val currentLength = editText.text.length
// We do nothing if the user is deleting
if (length > currentLength) {
return
}
if ((s.length == 1 && !s[0].isDigit())
|| (s.length == 2 && s[0].toString() == INITIAL_MONTH_ADD_ON && s[s.length - 1].toString() == SEPARATOR)
) {
editText.setText(DEFAULT_MONTH + SEPARATOR)
} else if (s.length == 1 && s[0].isBiggerThan(1)) {
editText.setText(INITIAL_MONTH_ADD_ON + s[0].toString() + SEPARATOR)
} else if (s.length == 2 && s[s.length - 1].toString() == SEPARATOR) {
editText.setText(INITIAL_MONTH_ADD_ON + s.toString())
} else if (s.length == 2 && s[s.length - 1].isBiggerThan(2)) {
var month = INITIAL_MONTH_ADD_ON + s[0].toString()
if (s[0].toString() == INITIAL_MONTH_ADD_ON) {
month = DEFAULT_MONTH
}
editText.setText(month + SEPARATOR + s[1].toString())
} else if (s.length == 2 && s[s.length - 1].toString() != SEPARATOR) {
editText.setText(editText.text.toString() + SEPARATOR)
} else if (s.length == 3 && s[s.length - 1].toString() != SEPARATOR) {
s.insert(2, SEPARATOR)
editText.setText(s.toString())
} else if (s.length > 3 && s[0].isBiggerThan(1)) {
editText.setText(INITIAL_MONTH_ADD_ON + s)
}
editText.setSelection(editText.text.toString().length)
}
private fun Char.isBiggerThan(num: Int): Boolean {
return this.isDigit() && this.toString().toInt() > num
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment