固定小数的Android Money Input

Android Money Input with fixed decimal(固定小数的Android Money Input)

本文介绍了固定小数的Android Money Input的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个仅以货币格式格式化输入的 edittext 条目?当用户输入 5 时,我希望输入看起来像$0.05",然后当他们输入 3 时,输入现在应该看起来像$0.53",最后他们输入 6,输入应该看起来像$5.36".

How do you create an edittext entry that formats input in money format only? When the user enters 5, I want the input to look like "$0.05" and when they then enter 3, the input should now look like "$0.53" and finally they enter 6 and the input should look like "$5.36".

推荐答案

ninjasense的完整解决方案基本可行,但存在一些问题:

ninjasense's complete solution basically works, but it has some issues:

  1. 每次在onTextChanged"处理程序中更改该字段的数据时,光标位置都会重置为该字段上的索引 0,这在输入货币值时会有点烦人.
  2. 它使用浮点数来格式化货币值,这可能会适得其反.

对于第一个问题我还没有解决方案,对于第二个这样的代码有效:

For the first problem I don't have solution yet, for the second one code like this works:

    @Override
    public void onTextChanged(CharSequence s, int start,
            int before, int count) {
        if(!s.toString().matches("^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$"))
        {
            String userInput= ""+s.toString().replaceAll("[^\d]", "");
            StringBuilder cashAmountBuilder = new StringBuilder(userInput);

            while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
                cashAmountBuilder.deleteCharAt(0);
            }
            while (cashAmountBuilder.length() < 3) {
                cashAmountBuilder.insert(0, '0');
            }
            cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
            cashAmountBuilder.insert(0, '$');

            cashAmountEdit.setText(cashAmountBuilder.toString());
        }

    }

这篇关于固定小数的Android Money Input的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:固定小数的Android Money Input

基础教程推荐