[英]Android EditText money input Regex without “$” symbol
我想輸入十進制數字,例如“ 23.50”,“ 250.75”。 下面的代碼提供了這一點,但是它在數字的前面放置了一個“ $”符號,例如“ $ 23.50”,“ $ 250.75” ..我想刪除美元符號並嘗試了幾種方法,但是我做不到。 如何更改正則表達式和顯示?
以下代碼:
inputAmount.setRawInputType(Configuration.KEYBOARD_12KEY);
inputAmount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
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,'$');
inputAmount.setText(cashAmountBuilder.toString());
// keeps the cursor always to the right
Selection.setSelection(inputAmount.getText(), cashAmountBuilder.toString().length());
}
}
});
@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, ' ');
edAmountAddMoney.setText(cashAmountBuilder.toString());
// keeps the cursor always to the right
Selection.setSelection(edAmountAddMoney.getText(), cashAmountBuilder.toString().length());
}
}
我用空格代替$,它對我有用
刪除行:
cashAmountBuilder.insert(0,'$');
並從正則表達式中刪除\\\\$
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.