繁体   English   中英

适用于马来西亚的 Android EditText 货币

[英]Android EditText currency for Malaysia

 Locale currency = new Locale("ms-my");
                //Locale of Malaysia
                if (!editable.toString().equals(current)) {
                    TransferAmount.removeTextChangedListener(this);
                    String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance(currency)
                            .getCurrencyInstance().getCurrency().getSymbol());
                    String cleanString = editable.toString().replaceAll(replaceable, "");

                    double parsed;
                    try {
                        parsed = Double.parseDouble(cleanString);
                    } catch (NumberFormatException e) {
                        parsed = 0.00;
                    }
                    NumberFormat formatter = NumberFormat.getCurrencyInstance();
                    formatter.setMaximumFractionDigits(0);
                    String formatted = formatter.format((parsed));

                    current = formatted;
                    TransferAmount.setSelection(formatted.length());
                    TransferAmount.addTextChangedListener(this);
                }

我想将货币设置为马来西亚,马来西亚国家代码是“ms-my”。 我想在文本前面添加马来西亚货币符号。 到底有没有?

简单的解决方案是将马来西亚国家代码“ms-my”添加为前缀

EditText editable = (EditText)findViewById(Your_id);
editable.addTextChangedListener(currencyFormatWatcher);

private final TextWatcher currencyFormatWatcher = new TextWatcher() {
    String prefix = "ms-my "; //"MYR "
    Locale currency = new Locale("ms-my");

    public void afterTextChanged(Editable s) {
        if(!s.toString().equals("")){
            editable.removeTextChangedListener(this);
            
            String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance(currency)
                        .getCurrencyInstance().getCurrency().getSymbol());
                String cleanString = editable.toString().replace(prefix, "").replaceAll(replaceable, "");
                double parsed;
                try {
                    parsed = Double.parseDouble(cleanString);
                } catch (NumberFormatException e) {
                    parsed = 0.00;
                }
                NumberFormat formatter = NumberFormat.getCurrencyInstance();
                formatter.setMaximumFractionDigits(0);
                String formatted = formatter.format((parsed));
                formatted = prefix.concat(formatted);
                
                            
            editable.setText(formatted);
            editable.setSelection(formatted.length());
            
            editable.addTextChangedListener(this);
        }
    }
};

检查这个答案

暂无
暂无

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

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