Last active
February 4, 2020 19:04
-
-
Save Eduardo-Nunes/b7e9059a359ea2148680ad0e50deaa8c to your computer and use it in GitHub Desktop.
Mast Text in Android without losing any char inputed
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
enum class StringMasks(val mask: String) { | |
CPF("###.###.###-##"), | |
PHONE("(##) #####-####"), | |
SMALL_DATE("##/##"), | |
CARD_NUMBER("#### #### #### ####") | |
} |
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
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 | |
} | |
} |
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 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