固定小数的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How can I use CClistview in COCOS2d Android?(如何在 COCOS2d Android 中使用 CClistview?)
cocos2d-android: how to display score(cocos2d-android:如何显示分数)
Sqlite database not copied from asset folder Android(Sqlite 数据库未从资产文件夹 Android 复制)
SQLite Database Copy Appears Corrupted When Generated by Device and not Emulator(SQLite 数据库副本在由设备而不是模拟器生成时出现损坏)
Android file copy(安卓文件拷贝)
Android how to detect Copy event of Edittext in android(Android如何在android中检测Edittext的Copy事件)