CurrencyTextWatcher用于货币,最后带有符号

时间:2017-03-06 16:18:26

标签: android android-edittext textwatcher

使用非常标准的文本观察器:

    @Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void afterTextChanged(Editable editable) {
    EditText editText = editTextWeakReference.get();
    if (editText == null) return;
    String s = editable.toString();
    editText.removeTextChangedListener(this);
    String cleanString = StringUtils.cleanString(s);
    BigDecimal parsed = new BigDecimal(cleanString).setScale(2, BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR);
    String formatted = NumberFormat.getCurrencyInstance(myLocale).format(parsed);
    editText.setText(formatted);
    editText.setSelection(formatted.length());
    editText.addTextChangedListener(this);
}

我的货币有问题,最后是符号。例如5.50€。我试图删除时,EditText中的文字没有变化。我知道发生了什么,而不是删除最后一个数字我删除货币符号。然后清理字符串,进行更改,并再次将字符串格式化为我的Locale。 我怎样才能解决这个问题?如何在afterTextChanged方法之前清理字符串? TextWatcher文档说在beforeTextChanged和onTextChanged中更改CharSequence是一个错误。

  

已找到解决方案。也许不是最好的,但它确实有效。与货币一样,货币符号在数字之前,货币符号在数字之后。

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    stringLengthBeforeChanges = s.length();
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void afterTextChanged(Editable editable) {
    EditText editText = editTextWeakReference.get();
    if (editText == null) return;
    String s = editable.toString();
    stringLengthAfterChanges = s.length();
    editText.removeTextChangedListener(this);
    String cleanString = StringUtils.cleanString(s);
    //this logic block used to correct removal digits when currency symbol after digits
    if(stringLengthBeforeChanges > stringLengthAfterChanges && !isLastCharacterDigit && cleanString.length() > 0){
        cleanString = cleanString.substring(0, cleanString.length()-1);
    }
    BigDecimal value;
    if(cleanString != null){
        value = cleanString.length() == 0 ? BigDecimal.ZERO : new BigDecimal(cleanString);
    } else {
        value = BigDecimal.ZERO;
    }
    BigDecimal parsed = value.setScale(2, BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR);
    String formatted = NumberFormat.getCurrencyInstance(myLocale).format(parsed);
    editText.setText(formatted);
    editText.setSelection(formatted.length());
    editText.addTextChangedListener(this);
}

0 个答案:

没有答案