android 的 EditText 十进制掩码

EditText decimal mask for android

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

最好的方法是什么?

我解决了这个问题:

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