本文介紹了固定小數的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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!