androidandroidxedittextpreference

How to set maximal length of EditTextPreference of AndroidX Library?


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?


Solution

  • 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.