Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit EditTextPreference to a range 1024:65535

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?

like image 612
wojciii Avatar asked Aug 06 '14 17:08

wojciii


1 Answers

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.

like image 165
wojciii Avatar answered Nov 14 '22 23:11

wojciii