简体   繁体   English

Android的EditText十进制蒙版

[英]EditText decimal mask for android

I'm working in an Android application and i want to create a decimal mask for editText in android. 我在一个Android应用程序中工作,我想为android中的editText创建一个十进制掩码。 I want a mask like a maskMoney jQuery plugin. 我想要像maskMoney jQuery插件这样的面具。 But in some cases my number will have 2 decimal places, 3 decimal places or will be a integer. 但是在某些情况下,我的数字将有2个小数位,3个小数位或整数。 I want do something like this: 我想做这样的事情:

  • When the EditText is created, come with a default value: 00.01 创建EditText时,带有默认值:00.01
  • If user press the number 2, the result should be: 00.12 如果用户按数字2,则结果应为:00.12
  • If user press the number 3, the result should be: 01.23 如果用户按数字3,则结果应为:01.23
  • If user press the number 4, the result should be: 12.34 如果用户按数字4,则结果应为:12.34
  • If user press the number 5, the result should be: 123.45 如果用户按数字5,则结果应为:123.45
  • If user press the number 6, the result should be: 1,234.56 如果用户按数字6,则结果应为:1,234.56

What's the best way to do that? 最好的方法是什么?

I resolved with this: 我解决了这个问题:

public static TextWatcher amount(final EditText editText, final String metric) {
    return new TextWatcher() {
        String current = "";

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().equals(current)) {
                editText.removeTextChangedListener(this);

                String cleanString = s.toString();

                if (count != 0) {
                    String substr = cleanString.substring(cleanString.length() - 2);

                    if (substr.contains(".") || substr.contains(",")) {
                        cleanString += "0";
                    }
                }

                cleanString = cleanString.replaceAll("[,.]", "");

                double parsed = Double.parseDouble(cleanString);
                DecimalFormat df = new DecimalFormat("0.00");
                String formatted = df.format((parsed / 100));

                current = formatted;
                editText.setText(formatted);
                editText.setSelection(formatted.length());

                editText.addTextChangedListener(this);
            }
        }

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

        public void afterTextChanged(Editable s) {}
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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