First letter capitalization for EditText

后端 未结 17 2066
傲寒
傲寒 2020-11-28 01:11

I\'m working on a little personal todo list app and so far everything has been working quite well. There is one little quirk I\'d like to figure out. Whenever I go to add a

17条回答
  •  不知归路
    2020-11-28 02:06

    Try This Code, it will capitalize first character of all words.

    - set addTextChangedListener for EditText view

    edt_text.addTextChangedListener(watcher);

    - Add TextWatcher

    TextWatcher watcher = new TextWatcher() {
        int mStart = 0;
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mStart = start + count;
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            String input = s.toString();
            String capitalizedText;
            if (input.length() < 1)
                capitalizedText = input;
            else if (input.length() > 1 && input.contains(" ")) {
                String fstr = input.substring(0, input.lastIndexOf(" ") + 1);
                if (fstr.length() == input.length()) {
                    capitalizedText = fstr;
                } else {
                    String sstr = input.substring(input.lastIndexOf(" ") + 1);
                    sstr = sstr.substring(0, 1).toUpperCase() + sstr.substring(1);
                    capitalizedText = fstr + sstr;
                }
            } else
                capitalizedText = input.substring(0, 1).toUpperCase() + input.substring(1);
    
            if (!capitalizedText.equals(edt_text.getText().toString())) {
                edt_text.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                    }
    
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                    }
    
                    @Override
                    public void afterTextChanged(Editable s) {
                        edt_text.setSelection(mStart);
                        edt_text.removeTextChangedListener(this);
                    }
                });
                edt_text.setText(capitalizedText);
            }
        }
    };
    

提交回复
热议问题