Android Money Input with fixed decimal(固定小数的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:
- 每次在onTextChanged"处理程序中更改该字段的数据时,光标位置都会重置为该字段上的索引 0,这在输入货币值时会有点烦人.
- 它使用浮点数来格式化货币值,这可能会适得其反.
对于第一个问题我还没有解决方案,对于第二个这样的代码有效:
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


- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01