How to validate an EditTextPreference value for a specific int range

蓝咒 提交于 2019-12-04 16:47:22

It might be more user-friendly to just clamp the value to the permitted range if an invalid value is entered, and notify the user with a Toast that you have done so.

If your range is small, such as 1-22, then you may even consider using a Spinner instead of an EditText so that the user can't enter an invalid value in the first place.

kingston

This is what I did:

    EditTextPreference pref = (EditTextPreference) findPreference(this.getString(R.string.my_setting_key));
    pref.getEditText().setFilters(new InputFilter[]{
            new InputFilter (){

                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {   
                    try {
                        int input = Integer.parseInt(dest.toString() + source.toString());
                        if (input<MAX_VALUE && input >0)
                            return null;
                    } catch (NumberFormatException nfe) { }     
                    return "";
                }
            }
    });

So the trick is that you can get and EditText from your EditTextPreference by using:

    pref.getEditText()

then you can set a filter. The filter should return null when everything is ok and an empty string when the char the user entered would make the text invalid.

See also here

You could use setPositivteButton and validate the input once the user hits Okay, if not okay, repop the dialog.

The InputFilter solution does not work, especially with selectAllOnFocus. If you cannot use the suggested picker/spinner alternative, for example, when you want to enforce a minimum but not a maximum, you can disable the OK button when the value is invalid like this:

public static void setNumberRange(final EditTextPreference preference, 
                                  final Number min, final Number max) {
    setNumberRange(preference, min, max, false);
}

public static void setNumberRange(final EditTextPreference preference,
                                  final Number min, final Number max, 
                                  final boolean allowEmpty) {

    preference.getEditText().addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(final Editable s) {

            Dialog dialog = preference.getDialog();
            if (dialog instanceof AlertDialog) {
                Button button = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
                if (allowEmpty && s.length() == 0) {
                    button.setEnabled(true);
                    return;
                }
                try {
                    if (min instanceof Integer || max instanceof Integer) {
                        int input = Integer.parseInt(s.toString());
                        button.setEnabled((min == null || input >= min.intValue()) && (max == null || input <= max.intValue()));
                    } else if (min instanceof Float || max instanceof Float) {
                        float input = Float.parseFloat(s.toString());
                        button.setEnabled((min == null || input >= min.floatValue()) && (max == null || input <= max.floatValue()));
                    } else if (min instanceof Double || max instanceof Double) {
                        double input = Double.parseDouble(s.toString());
                        button.setEnabled((min == null || input >= min.doubleValue()) && (max == null || input <= max.doubleValue()));
                    }
                } catch (Exception e) {
                    button.setEnabled(false);
                }
            }
        }
    });
}

This allows you to specify minimum and/or maximum values as Integer, Float or Double (pass null for unbounded). Optionally you can allow/disallow empty values. (Values invalid initially are accepted.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!