如何创建仅以货币格式格式化输入的编辑文本条目?当用户输入 5 时,我希望输入看起来像“$0.05”,然后当他们输入 3 时,输入现在应该看起来像“$0.53”,最后输入 6 并且输入应该看起来像“$5.36”。
ninjasense 的完整解决方案基本上可以工作,但它有一些问题:
- 每次在“onTextChanged”处理程序中更改字段数据时,光标位置都会重置为字段上的索引 0,这在输入货币值时会有点烦人。
- 它使用浮点数来格式化货币值,这可能会适得其反。
对于第一个问题,我还没有解决方案,对于第二个问题,这样的代码有效:
@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());
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)