Skip to content

Instantly share code, notes, and snippets.

@gokmenbayram
Last active March 20, 2024 15:06
Show Gist options
  • Save gokmenbayram/81b4f7a41c8f0966c0765df4a498e674 to your computer and use it in GitHub Desktop.
Save gokmenbayram/81b4f7a41c8f0966c0765df4a498e674 to your computer and use it in GitHub Desktop.
AllowOnlyLettersAndNoConsecutiveSpaces
fun EditText.allowOnlyLettersAndNoConsecutiveSpaces() {
filters = arrayOf(InputFilter { enteredText, start, end, dest, dstart, dend ->
if (enteredText.toString().matches("[a-zA-ZğüşıöçĞÜŞİÖÇ ]*".toRegex())) {
when {
//If the first character is entered as empty
enteredText.isBlank() && dest.isEmpty() -> ""
//If the entered character is empty and entered as empty at the first index
enteredText.isBlank() && dend == 0 -> ""
//If a space is intended to be entered between two letters
enteredText.isBlank() && dest[dend - 1] != ' ' -> " "
//If a second space is intended to be entered after the last character.
enteredText.isBlank() || (enteredText[0] == ' ' && dest[dend - 1] == ' ') -> ""
//If a second space is intended to be entered between two characters.
enteredText.last() == ' ' && dest.length != dend -> enteredText.trimEnd()
else -> {
null
}
}
} else {
null
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment