how to set only numeric value for EditTextPreference in android?

I use an androidX library because this library has a possibility to customize an input type of EditTextPreference dialog. AndroidX is a major improvement to the original Android Support Library so is suggested that everybody use this library. You can read more about AndroidX here.

Here is my code where I use EditTextPreference inside of onCreatePreference method:

 @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preference, rootKey);



androidx.preference.EditTextPreference editTextPreference = getPreferenceManager().findPreference("use_key_from_editTextPreference_in_xml_file");
editTextPreference.setOnBindEditTextListener(new androidx.preference.EditTextPreference.OnBindEditTextListener() {
            @Override
            public void onBindEditText(@NonNull EditText editText) {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);

            }
        });

       }

After you use this code and click on editTextPreference, the dialog will pop up and your keyboard input type will be only numeric.


EditTextPreference widgets should take the same attributes as a regular EditText, so use:

android:inputType="number"

Or more specifically use:

android:inputType="numberDecimal"
android:digits="0123456789"

since you want to limit the input to a port number only.

Tags:

Android