Search code examples
androidsharedpreferencesandroid-preferences

Is it possible to restrict a EditTextPreference to numbers?


I have an EditTextPreference in the settings of my app for which I only want to accept positive decimal numbers:

<EditTextPreference
    android:key="annual_vacation_setting"
    android:title="@string/enter_annual_vacation"
    android:defaultValue="@string/default_annual_vacation"
    android:inputType="numberDecimal"
    android:selectAllOnFocus="true" />

Unfortunately, the inputType attribute doesn't seem to have any effect. The user can input arbitrary strings.


Solution

  • Solution 1

    You need to set inputType to its EditText after onBinding:

    editTextPrefView.setOnBindEditTextListener { editText ->
        editText.inputType = InputType.TYPE_CLASS_NUMBER
    }
    

    Solution 2

    Use this FIX library. It will let you directly set android:inputType=numberDecimal to EditTextPreference in XML