問題描述
如何創(chuàng)建一個(gè)僅以貨幣格式格式化輸入的 edittext 條目?當(dāng)用戶輸入 5 時(shí),我希望輸入看起來像$0.05",然后當(dāng)他們輸入 3 時(shí),輸入現(xiàn)在應(yīng)該看起來像$0.53",最后他們輸入 6,輸入應(yīng)該看起來像$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"處理程序中更改該字段的數(shù)據(jù)時(shí),光標(biāo)位置都會(huì)重置為該字段上的索引 0,這在輸入貨幣值時(shí)會(huì)有點(diǎn)煩人.
- 它使用浮點(diǎn)數(shù)來格式化貨幣值,這可能會(huì)適得其反.
對(duì)于第一個(gè)問題我還沒有解決方案,對(duì)于第二個(gè)這樣的代碼有效:
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());
}
}
這篇關(guān)于固定小數(shù)的Android Money Input的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!