how to set only numeric value for EditTextPreference in android. I want a user to enter a port number not sure how can I put the limitation there
I am using this code, user can enter any string. Want to limit the user to atleast numbers only
<EditTextPreference
android:defaultValue="4444"
android:key="port"
android:title="Port"
android:dependency="service_on"
/>
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.
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.
Using androidx.preference
library, since androidx.preference:preference:1.1.0-alpha02
which is realeased on 2018.12.17, the library adds EditTextPreference.OnBindEditTextListener
interface, which allows you to customize the EditText displayed in the corresponding dialog after the dialog has been bound.
So in this case, all you have to do is to add the Kotlin code below.
val editTextPreference = preferenceManager.findPreference<EditTextPreference>("YOUR_PREFERENCE_KEY")
editTextPreference.setOnBindEditTextListener { editText ->
editText.inputType = InputType.TYPE_CLASS_NUMBER
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With