How to set maximal length of EditTextPreference of AndroidX Library?

1.3k Views Asked by At

Recently, I migrate my android project to AndroidX and I use the EditTextPreference from AndroidX library. Now, I want to set the maximum length of the EditTextPreference to let say 50. I have tried to use:

android:maxLength="50"

but it's not working.

It seems that all android namespace won't work with the EditTextPreference and there is no code suggestion so I cannot find any related code to set the maximum length. How can I set the maximum length?

3

There are 3 best solutions below

2
tadiuzzz On BEST ANSWER

You need find your EditTextPreference by key, then set onBindEditTextListener to it and change layout attributes at the onBindEditText method:

EditTextPreference preference = findPreference("edit_text_preference_key");
    preference.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
        @Override
        public void onBindEditText(@NonNull EditText editText) {
            editText.setInputType(InputType.TYPE_CLASS_NUMBER); // set only numbers allowed to input
            editText.selectAll(); // select all text
            int maxLength = 2;
            editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)}); // set maxLength to 2
        }
    });

You can put this code to onResume() method of yout PreferencesFragment or PreferencesActivity.

4
Mehul Solanki On

You may try with java code, that will works. Here is snipped.

EditText et = (EditText) findViewById(R.id.myeditText);
et.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(50) }); // maximum length is 50

I hope that will help you.

0
t0m On

This is the code to set maximal length (in this case 10) of EditTextPreference:

final EditTextPreference prefCustomText = findPreference(ActivityPreferences.PREF_DISPLAY_CUSTOM_TEXT);
prefCustomText.setOnBindEditTextListener(editText -> {
    editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
});

And I'm adding information as wrote @Viktor Brešan:

I think you should append the new InputFilter to ones that might have been added to EditText previously. You can get them by calling editText.getFilters()