android edittext minmum and maximum value

我们两清 提交于 2020-01-13 03:15:30

问题


I am in development of an android app.. actually i need to set a minimum and maximum value for an editext entry my minimum value is 18 and maximum is 65.I did the exact code of this

package com.test;

import android.text.InputFilter;
import android.text.Spanned;

public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    @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 (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) { }     
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}




EditText et = (EditText) findViewById(R.id.myEditText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "12")});

I got this code fro this site only ... Is there a way to define a min and max value for EditText in Android? actually this for values between 1 and 12 and for that value it is working fine but when i changed for my value 18 and 45 it is not working ... can anyone please help me.. what change i have to be done for this ...


回答1:


You should replace the line:

int input = Integer.parseInt(dest.toString() + source.toString());

With

int input = Integer.parseInt(source.toString());

Look at Can someone help me with the parameters to the Android InputFilter "filter" method? (plus regex) to understand why



来源:https://stackoverflow.com/questions/16621210/android-edittext-minmum-and-maximum-value

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