androidandroid-edittextandroid-inputtype

InputType doesn't work when text is set with setText


I have set android:inputType="text|textCapWords" to my EditText. When I type something in the field, the first letter is correctly capitalised, but if I set a full capitalised (or full lowercase) text using the setText() method, the text remains fully capitalised (or in lowercase).

How can I use setText for the text to comply with the input type?


Solution

  • As @Amarok suggests

    This is expected behavior. You have to format the text yourself before using the setText() method

    But if you want to format your text just like android:inputType="text|textCapWords you can use the following method:

    public static String modifiedLowerCase(String str){
            String[] strArray = str.split(" ");
            StringBuilder builder = new StringBuilder();
            for (String s : strArray) {
                String cap = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
                builder.append(cap + " ");
            }
            return builder.toString();
        }
    

    and use it like

    textView.setText(modifiedLowerCase("hEllo worLd"));
    

    It will convert it like :

    Hello World