简体   繁体   中英

Allow AndroidX EditTextPreference to only accept letters

I have an EditTextPreference set up with a filter to limit it's size, like so:

pref.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
            @Override
            public void onBindEditText(@NonNull EditText editText) {
                editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10)});
            }
        });

I want to also limit it to only accept letters (not just a-zA-Z, since the app accepts more than one language). How can I go about doing this?

I have tried many filters before, including all of those suggested in these questions and similar:

Making an EditText field accept only letters and white spaces in Android

Edittext only allow letters (programmatically)

With filters like those, whenever a number is inputted and then a letter, I get issues like:
- The whole text disappears
- The whole text gets duplicated
- The last few characters get duplicated

I also tried changing the XML by adding and android:digits , but no matter what it doesn't restrict the input at all.
Every inputType I've tried so far does not restrict the keyboard to only letters.

EDIT: I figured it out, answer below.

I just added a TextWatcher to the EditText, and replaced the text with a regex, like this:

editText.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) {
                        editText.removeTextChangedListener(this);
                        String replaced = s.toString().replaceAll("[^[:alpha:] ]", "");
                        editText.setText(replaced);
                        editText.setSelection(replaced.length());
                        editText.addTextChangedListener(this);
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });

This lets letters be added in, but when anything else is typed, it doesn't show up and isn't saved anywhere. The setSelection() method is there to put the cursor at the end of the string, otherwise it resets to the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM