Trying to change color of English text in EditText field's input.
Add Textwatcher
in Edittext and call method in afterTextchanged
method.
val regEng = Pattern.compile("[a-zA-Z]")
var editWatcher = object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
onChanged()
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, start: Int, before: Int, count: Int) {
}
}
private fun onChanged() {
var spanString = SpannableStringBuilder()
var input = et_form.text.toString()
for (i in 0 until input.length) {
val char = input[i].toString()
var matcher = regEng.matcher(char)
if (matcher.find()) {
val engspan = SpannableString(char).apply {
setSpan(ForegroundColorSpan(Color.RED), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
spanString.append(engspan)
} else {
val normal = SpannableString(char).apply {
setSpan(ForegroundColorSpan(Color.BLACK), i, char.length - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
spanString.append(normal)
}
}
}
But it doesn't work and when I add code
edittext.text = spanString
It doesn't stop and keep calling onchanged
method..