Skip to content

Instantly share code, notes, and snippets.

@Eduardo-Nunes
Last active February 4, 2020 19:04
Show Gist options
  • Save Eduardo-Nunes/b7e9059a359ea2148680ad0e50deaa8c to your computer and use it in GitHub Desktop.
Save Eduardo-Nunes/b7e9059a359ea2148680ad0e50deaa8c to your computer and use it in GitHub Desktop.
Mast Text in Android without losing any char inputed
enum class StringMasks(val mask: String) {
CPF("###.###.###-##"),
PHONE("(##) #####-####"),
SMALL_DATE("##/##"),
CARD_NUMBER("#### #### #### ####")
}
class MaskTextWatcher(private val mask: String) : TextWatcher {
private var isRunning = false
private var isDeleting = false
override fun beforeTextChanged(charSequence: CharSequence, start: Int, count: Int, after: Int) {
isDeleting = count > after
}
override fun onTextChanged(charSequence: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(editable: Editable) {
if (isRunning || isDeleting) {
return
}
isRunning = true
var index = 0
for (m in editable.toString().trim().unmask().applyMask(mask).toCharArray()) {
try {
if (editable[index] != m) {
editable.insert(index, m.toString())
}
} catch (e: Exception) {
break
}
index++
}
isRunning = false
}
}
fun String.unmask(): String {
return replace("[.]".toRegex(), "").replace("[-]".toRegex(), "").replace("[/]".toRegex(), "")
.replace("[(]".toRegex(), "").replace("[ ]".toRegex(), "").replace("[:]".toRegex(), "")
.replace("[)]".toRegex(), "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment