I have a EditTextPreference defined as:
<EditTextPreference
android:defaultValue="8888"
android:key="someKey"
android:title="SomeString"
android:inputType="number"
>
EditTextPreference uses an EditText internally which can be obtained with EditTextPreference.getEditText()
.
I would like to limit the number the user can input to a range of integers between 1024 and 65535. How can I do that?
I tried to use both an InputFilter and a TextWatcher without success.
Any ideas?
As you might have guessed I am trying to validate inputting a network port. Maybe I should use some other kind of input for this?
I am answering this myself because no other answers were what I wanted.
final int minPort = 1024;
final int maxPort = 2048;
final EditTextPreference editTextPreference = (EditTextPreference)findPreferenceByResId(R.string.pref_telnet_server_port_key);
editTextPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int val = Integer.parseInt(newValue.toString());
if ((val > minPort) && (val < maxPort)) {
Log.d(LOGTAG, "Value saved: " + val);
return true;
}
else {
// invalid you can show invalid message
Toast.makeText(getApplicationContext(), "error text", Toast.LENGTH_LONG).show();
return false;
}
}
});
This way you show a toast when the user enters an invalid number and do not save the entered value. This works for me and is simpler than the custom NumberPicker preference which I was unable to make work.
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