0

I want to capizalize every word typed in EditText inside onTextChanged. I've tried some solutions but none of them worked. Problem what I'm facing is if you change capitalize letter on keyboard and you will type James JoNEs it should repair that String to correct form after you type E character to Jone. This is not working with default android:inputType="textCapWords". I've used some function what I've found but it is not working at all.

fun onFieldChanged(s: String, tv: TextWatcher, et: EditText) {
    et.removeTextChangedListener(tv)
    val changedString = capitalizeFirstLetterWord(s)
    with(et) {
        text.clear()
        append(changedString)
        setSelection(changedString.length)
    }
    et.addTextChangedListener(tv)
}

fun capitalizeFirstLetterWord(s: String): String{
    var finalStr = ""
    if(s != "") {
        val strArray = s.split("[\\s']")
        if (strArray.isNotEmpty()) {
            for(i in strArray.indices){
                finalStr+= capitalize(strArray[i])
            }
        }
    }
    return finalStr
}
martin1337
  • 2,384
  • 6
  • 38
  • 85
  • 2
    Refer to this [answer link](https://stackoverflow.com/questions/15961813/in-android-edittext-how-to-force-writing-uppercase/15961909). You will find 2 methods. – Ankit Gupta Oct 10 '19 at 09:57

1 Answers1

3

You can try to achieve that with something like this

"yourString".split(" ").map { it.toLowerCase().capitalize() }.joinToString(" ")

  • 1
    toLowerCase was the problem. Because capitalize will not change whole string to lower. It checks just first character – martin1337 Oct 10 '19 at 11:04