简体   繁体   中英

How to limit the EditText input only allow 3 digits of number either integer or decimal

As the title says, I set up an EditText in my activity and want to limit the input to only numbers. However, it doesn't matter if it is a decimal number or integer. I do require the number of digits is limited at 3. For example, the input of '123', '1.23', '12.3' are all legit input.

'1234', '123.', '.123' are all illegal input.

I have tried to set up

android:inputType = "numberDecimal"

in the xml file.

And set the max length to 4.

edit:

I also tried following code:

InputFilter filter = new InputFilter() {

    //^\-?(\d{0,5}|\d{0,5}\.\d{0,3})$
    //^\-?(\d{0,3}|\d{0,2}\.\d{0,1}|\d{0,1}\.\d{0,2})$
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (end > start) {
            // adding: filter
            // build the resulting text
            String destinationString = dest.toString();
            String resultingTxt = destinationString.substring(0, dstart) + source.subSequence(start, end) + destinationString.substring(dend);
            // return null to accept the input or empty to reject it
            return resultingTxt.matches("^\\-?(\\d{0,3}|\\d{0,2}\\.\\d{0,1}|\\d{0,1}\\.\\d{0,2})$") ? null : "";
        }

        return null;
    }
};

I did modified the regex from the sample code mentioned by @Suman Dash. My understanding of the regex

^\-?(\d{0,3}|\d{0,2}\.\d{0,1}|\d{0,1}\.\d{0,2})$

is to allow certain pattern of number input such as #.##, ##.# and ###. When I test the code, the pattern #.## and ##.# are working fine, but the pattern ### also allow input like ".##", for example, ".88" as legit input. And it treats the decimal point as a legit number, so I can only input ".88", not ".123". Anyway, I don't want any number starts with the decimal point. How can I eliminate that? What's the best way to achieve this goal? Thanks!

InputFilter filter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        for (int i = start; i < end; ++i)
        {
            if (!Pattern.compile("[1234567890\.]*").matcher(String.valueOf(source.charAt(i))).matches())
            {
                return "";
            }
        }
        return null;
    }
};
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EditText ntxt =(EditText)findViewById(R.id.numberEditTextbox) ;
    ntxt.setFilters(new InputFilter[]{filter,new InputFilter.LengthFilter(4)});

}

This code may help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM