本文介绍了android的EditText十进制蒙版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我在一个Android应用程序中工作,我想为android中的editText创建一个十进制掩码.我想要像maskMoney jQuery插件这样的面具.但是在某些情况下,我的数字将有2个小数位,3个小数位或整数.我想做这样的事情:

I'm working in an Android application and i want to create a decimal mask for editText in android. I want a mask like a maskMoney jQuery plugin. But in some cases my number will have 2 decimal places, 3 decimal places or will be a integer. I want do something like this:

  • 创建EditText时,默认值为00.01
  • 如果用户按数字2,则结果应为:00.12
  • 如果用户按数字3,则结果应为:01.23
  • 如果用户按数字4,则结果应为:12.34
  • 如果用户按数字5,则结果应为:123.45
  • 如果用户按数字6,则结果应为:1,234.56

做到这一点的最佳方法是什么?

What's the best way to do that?

推荐答案

我对此进行了解决:

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) {}
    };
}

这篇关于android的EditText十进制蒙版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 05:09