Android EditText/TextView how to make each word start with uppercase and all remaining characters of words to be lowercase

laaptu picture laaptu · Jan 16, 2014 · Viewed 23.8k times · Source

I have already used following options to make each starting letter of a word Uppercase

 <EditText
    android:inputType="text|textCapWords"/>

While typing the user has option on the keyboard to change the case of letter i.e. the user with this option can easily type lowercase letters.

Further,I want text on my EditText to be on this format

Each Starting Letter Of A Word Must Be In Uppercase And All Other Letter Of The Word Be In Lowercase.

Meaning,when the user inputs

each StArting LeTTer of a word musT be in uppercase and all other leTTer of the word be in lowercase

, it will be automatically converted to above format.

I have tried using TextWatcher and string.split(\\s+) to get all the words and then make each and every word to follow the above format. But I always end up getting error. So if there is any solution,it would be great.I want this to work in the manner InputFilter.AllCaps.

This is my code so far

private void changeToUpperCase(String inputString) {
    if (inputString != null && inputString.trim().length() > 0) {
        // businessName.addTextChangedListener(null);
        String[] splitString = inputString.split("\\s+");
        int length = splitString.length;
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            String convertedString = splitString[i];
            stringBuffer.append(Character.toUpperCase(convertedString
                    .charAt(0)));
            stringBuffer.append(convertedString.substring(1).toLowerCase());
            stringBuffer.append(" ");
        }
        Log.i("changed String", stringBuffer.toString());
        // businessName.setText(stringBuffer.toString());
        stringBuffer.delete(0, stringBuffer.length());
        stringBuffer = null;
        // businessName.addTextChangedListener(this);
    }
}

This function I am calling from TextWatcher, afterTextChanged(Editable s)

Answer

Shailendra Madda picture Shailendra Madda · Jan 16, 2014

In the layout xml, add android:capitalize="sentences"

The options for android:capitalize are following :

android:capitalize="none" : which won't automatically capitalize anything.

android:capitalize="sentences" : which will capitalize the first word of each sentence.

android:capitalize="words" : which will capitalize the first letter of every word.

android:capitalize="characters" : which will capitalize every character.

Update:

As android:capitalize is deprecated now need to use:

android:inputType="textCapWords"