Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
Bernhard Josephus Avatar asked May 14 '19 10:05

Bernhard Josephus


1 Answers

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.

like image 98
tadiuzzz Avatar answered Oct 24 '22 12:10

tadiuzzz