Is there a way to create a preference in a PreferenceFragment that accepts only integer values? I could implement an EditTextPreference and register an OnPreferenceChangeListener in which I could reject the change if the user enters a a string that is not a number, but I would prefer something that is meant for holding only numbers and that does not allow users to enter anything else, maybe showing only a dial pad keyboard.. I don't such a preference exist, since every descendant of Preference is mapped onto a Boolean (CheckBoxPreference), a String (*EditTextPreference) or a String array (MultiSelectListPreference), i.e. there are no preferences mapped onto integers, but maybe some of you can give me an hint or at least tell me if there are better solutions than the one I've proposed above.
Solution proposed by Grey:
EditText editText = ((EditTextPreference)
findPreference("intent_property")).getEditText();
editText.setKeyListener(new NumberKeyListener() {
@Override
public int getInputType() {
// The following shows the standard keyboard but switches to the view
// with numbers on available on the top line of chars
return InputType.TYPE_CLASS_NUMBER;
// Return the following to show a dialpad as the one shown when entering phone
// numbers.
// return InputType.TYPE_CLASS_PHONE
}
@Override
protected char[] getAcceptedChars() {
return new String("1234567890").toCharArray();
}
});
Shorter solution, which does not allow varying the keyboard to dialpad but requires less code:
EditText editText = ((EditTextPreference)
findPreference("intent_property")).getEditText();
editText.setKeyListener(new DigitsKeyListener());
I don't like just one thing about this solution: the user can enter 0000 and it is accepted and saved in the shared preference (which is a String) as "0000".. this requires you to implement a OnSharedPreferenceChangeListener to intercept changes to shared preferences and remove leading zeros in this preference or implement a change listener directly on this preference and return false to refuse numbers with trailing zeros (tell me if there is a better solution to this last problem which does not involve implementing your own Preference). It would be beautiful if we could modify the newValue in OnPreferenceChangeListener..