How to capitalize every letter in an Android EditText?

后端 未结 10 1679
离开以前
离开以前 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:18

    You need to tell it it's from the "class" text as well:

    inputs[i] = new EditText(this);
    inputs[i].setWidth(376);
    inputs[i].setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
    tFields.addView(inputs[i]);
    

    The input type is a bitmask. You can combine the flags by putting the | (pipe) character in the middle, which stands for the OR logic function, even though when used in a bitmask like this it means "this flag AND that other flag".

    (This answer is the same as Robin's but without "magic numbers", one of the worst things you can put in your code. The Android API has constants, use them instead of copying the values and risking to eventually break the code.)

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

    This will make all the characters uppercase when writing.

    edittext.setFilters(new InputFilter[] {new InputFilter.AllCaps()});
    

    Original answer here.

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

    try using this single line of code in your xml:

    android:capitalize="sentences"
    
    0 讨论(0)
  • 2021-01-07 18:22

    I know this question is a bit old but here is explained how to do it in different ways:

    Applying UpperCase in XML

    Add the following to the EditText XML:

    android:inputType="textCapCharacters"
    

    Applying UpperCase as the only filter to an EditText in Java

    Here we are setting the UpperCase filter as the only filter of the EditText. Notice that this method removes all the previously added filters.

    editText.setFilters(new InputFilter[] {new InputFilter.AllCaps()});
    

    Adding UpperCase to the existing filters of an EditText in Java

    To keep the already applied filters of the EditText, let's say inputType, maxLength, etc, you need to retrieve the applied filters, add the UpperCase filter to those filters, and set them back to the EditText. Here is an example how:

    InputFilter[] editFilters = editText.getFilters();
    InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
    System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
    newFilters[editFilters.length] = new InputFilter.AllCaps();  
    editText.setFilters(newFilters);
    
    0 讨论(0)
  • 2021-01-07 18:22

    As of today, Its

    android:inputType="textCapCharacters"

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

    This would work

        inputs[i] = new EditText(this);
        inputs[i].setWidth(376);
        inputs[i].setInputType(0x00001001);
        tFields.addView(inputs[i]);
    

    0x00001001 corresponds to "textCapCharacters constant.

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