通过对EditTextView的输入变化进行监听,举例,保存小数点后两位
int n=2;
etMoney.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
if (s.toString().contains(".")) {
if (s.length() - 1 - s.toString().indexOf(".") > n) {
s = s.toString().subSequence(0,
s.toString().indexOf(".") + (n+1));
etMoney.setText(s);
etMoney.setSelection(s.length());
}
}
if (s.toString().trim().substring(0).equals(".")) {
s = "0" + s;
etMoney.setText(s);
etMoney.setSelection(2);
}
if (s.toString().startsWith("0")
&& s.toString().trim().length() > 1) {
if (!s.toString().substring(1, 2).equals(".")) {
etMoney.setText(s.subSequence(0, 1));
etMoney.setSelection(1);
return;
}
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});