[Android] Alphabet uppercase limit and length limit in EditText

Alphabet uppercase limit in EditText

EditText, used as an input box in Android apps, I want to limit the input to only uppercase letters! For iOS, refer to [iOS] Alphabet capitalization limit and length limit in UITextField.

environment

Host: Windows 10 Android Studio: 3.3.2 Java

When setting attributes

Open the layout, select the desired UITextField, and open the attributes: digits in the right pane for editing. image.png

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

When applying other constraints together

Filter preparation

MyActivity.java


    //Alphabet filter
    private  InputFilter alphabetFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            if (source.toString().matches("^[a-zA-Z]+$")) {
                return source.toString().toUpperCase(Locale.ROOT);
            } else {
                return "";
            }
        }
    };

Filter settings for EditText

  1. Implemented in the onCreate function, etc.

MyActivity.java


    InputFilter myFilters[] = {alphabetFilter, new InputFilter.LengthFilter(5)}; //Uppercase + alphabet filter + length filter

    EditText targetEditText = findViewById(R.id.edittext_target);
    targetEditText.setFilters(myFilters);

Actual machine test

You cannot enter numbers with the keyboard, the length is limited, Make sure that if you enter lowercase letters, they will be automatically converted to uppercase.

Thank you for your hard work!

Recommended Posts

[Android] Alphabet uppercase limit and length limit in EditText
Java to C and C to Java in Android Studio
Represents "next day" and "previous day" in Java / Android
[Android / Java] Screen transition and return processing in fragments
Asynchronous processing and Web API integration in Android Studio