1

Trying to change edittext's input color when character is alphabet. so I added textWatcher in edittext and check it with regex. It looks like working OK-ish but doesn't work when input String start with English. When input's first String start with alphabet then number text also change color as Red even though it is not in regex result.

 val regEng = "[a-zA-Z]".toRegex()

  private fun setResources() {
        et_form.addTextChangedListener(editWatcher)
    }

    var editWatcher = object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {
            p0.let { et ->
            regEng.findAll(et.toString()).map { it.range }.forEach { range ->
                    Log.d("dddd", et.toString()[range.first].toString())
                    et?.setSpan(ForegroundColorSpan(Color.RED), range.first, range.first + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
               }
            }
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, start: Int, before: Int, count: Int) {
        }

    }

Here is what I tried. If I input 12ABC then output looks like enter image description here

It I input ABC12 then output looks like enter image description here

coooldoggy
  • 47
  • 5

1 Answers1

1

You would need to use HTML text to accomplish this.

String htmlText = et.replace(textToBeColored,"<font 
                color='#c5c5c5'>"+textToBeColored +"</font>");
                et?.setText(Html.fromHtml(htmlText);

I would also potentially change the regex to be

(\D) <- Match any none digit character

([a-zA-Z]) <-- would group them resulting in less calls to replace

Scott Johnson
  • 707
  • 5
  • 13