How can I limit the EditText box input to two characters after a decimal place?

跟風遠走 提交于 2019-12-14 02:06:42

问题


i'm working on an android application with an EditText box. In this box i want the user to enter currency.

I have already restricted the keyboard to numbers and decimals using the handy android:inputType="numberDecimal" but i would like to be able to stop the user from entering more than two digits after the decimal place (so that the content is saved as a currency and also just because i think it's important that the user is clear about what they're entering).

However i don't have much programming experience and i don't know where to start looking (validation is a pretty huge topic haha). A bit of googling and it sounds like i should make my own extension of the InputFilter class but i'm not sure how to go about that or if there's a better way. So Any advice would really be appreciated!


回答1:


Use the InputFilter http://developer.android.com/reference/android/text/InputFilter.html




回答2:


Try this

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(2)});

DecimalDigitsInputFilter

public class DecimalDigitsInputFilter implements InputFilter {
    Pattern mPattern;
    public DecimalDigitsInputFilter(int digitsAfterZero) {
        mPattern=Pattern.compile("[0-9]+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
    }
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        Matcher matcher=mPattern.matcher(dest);       
        if(!matcher.matches())
            return "";
        return null;
    }
}



回答3:


To limit the user from not entering more than two digits after decimal point just use the following code.

myEditText1 = (EditText) findViewById(R.id.editText1);  
myEditText1.setInputType(3);

The number '3' does the trick. Hope it helps!



来源:https://stackoverflow.com/questions/4769577/how-can-i-limit-the-edittext-box-input-to-two-characters-after-a-decimal-place

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