主要是针对 需要限制小数位数的输入框做的监听处理
public class NumTextWatcher implements TextWatcher {
private int defaultRetain = 2;
private EditText edit;
public NumTextWatcher(@NonNull EditText edit, int retainDecimal, AfterTextChange chang) {
this.defaultRetain = retainDecimal;
this.edit = edit;
this.mChange = chang;
}
@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 s) {
CharSequence afterChange = s.toString();
if (TextUtils.isEmpty(afterChange)) {
if (mChange != null)
mChange.afterText(afterChange);
return;
}
//删除“.”后面超过2位后的数据
if (afterChange.toString().contains(".")) {
int first = afterChange.toString().indexOf(".");
int last = afterChange.toString().lastIndexOf(".");
if (first == last) {
if (afterChange.length() - 1 - first > defaultRetain) {
afterChange=afterChange.subSequence(0, first + defaultRetain + 1);
this.edit.setText(afterChange);
this.edit.setSelection(afterChange.length()); //光标移到最后
}
} else {
afterChange=afterChange.subSequence(0, last);
this.edit.setText(afterChange.subSequence(0, last));
this.edit.setSelection(afterChange.length()); //光标移到最后
}
}
//如果"."在起始位置,则起始位置自动补0
if (afterChange.toString().trim().substring(0).equals(".")) {
afterChange = "0" + afterChange;
this.edit.setText(afterChange);
this.edit.setSelection(2); //光标移到最后
}
//如果起始位置为0,且第二位跟的不是".",则无法后续输入
if (afterChange.toString().startsWith("0") && afterChange.toString().trim().length() > 1) {
if (!afterChange.toString().substring(1, 2).equals(".")) {
this.edit.setText(afterChange.subSequence(0, 1));
this.edit.setSelection(1);
return;
}
}
if (mChange != null)
mChange.afterText(afterChange);
}
private AfterTextChange mChange;
public interface AfterTextChange {
void afterText(CharSequence after);
}
}
网友评论