How to capitalize every letter in an Android EditText?

后端 未结 10 1680
离开以前
离开以前 2021-01-07 17:41

I have an array of editTexts which I make like this:

        inputs[i] = new EditText(this);
        inputs[i].setWidth(376);
        inputs[i].setInputType(         


        
相关标签:
10条回答
  • 2021-01-07 18:31

    Just use String.toUpperCase() method.

    example :

    String str = "blablabla";
    editText.setText(str.toUpperCase()); // it will give : BLABLABLA
    

    EDIT :

    add this attribute to you EditText Tag in your layout xml :

     android:textAllCaps="true"
    

    OR:

    If you want whatever the user types to be uppercase you could implement a TextWatcher and use the EditText addTextChangedListener to add it, an on the onTextChange method take the user input and replace it with the same text in uppercase.

    editText.addTextChangedListener(upperCaseTextWatcher);
    
    final TextWatcher upperCaseTextWatcher = new TextWatcher() {
    
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }
    
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        editText.setText(editText.getText().toString().toUpperCase());
        editText.setSelection(editText.getText().toString().length());
    }
    
    public void afterTextChanged(Editable editable) {
    }
    
    };
    
    0 讨论(0)
  • 2021-01-07 18:40

    You can try this:

    android:inputType="textCapCharacters"
    

    It worked for me. =)

    0 讨论(0)
  • 2021-01-07 18:40

    For some reason adding the xml did not work on my device.

    I found that a Text Filter works for to uppercase, like this

        EditText editText = (EditText) findViewById(R.id.editTextId);
    
        InputFilter toUpperCaseFilter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
    
                StringBuilder stringBuilder = new StringBuilder();
    
                for (int i = start; i < end; i++) {
                    Character character = source.charAt(i);
                    character = Character.toUpperCase(character); // THIS IS UPPER CASING
                    stringBuilder.append(character);
    
                }
                return stringBuilder.toString();
            }
    
        };
    
        editText.setFilters(new InputFilter[] { toUpperCaseFilter });
    
    0 讨论(0)
  • 2021-01-07 18:43

    To capitalize the first word of each sentence use :

    android:inputType="textCapSentences"

    To Capitalize The First Letter Of Every Word use :

    android:inputType="textCapWords"

    To Capitalize every Character use :

    android:inputType="textCapCharacters"

    0 讨论(0)
提交回复
热议问题