我有一个编辑文字可以填写金额。因此,我添加了文本监视程序,但是我不希望用户连续按下“ 0000 ...”来将其设置为“ 0000000 ...”,而应该像计算器一样仅显示一次“ 0”
我该怎么做?
private void setAmount() {
etAmount.addTextChangedListener(new 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) {
if (s.length() == 1) {
if (s.toString().equals("0")) {
etAmount.setText("0");
}
}
//Not working
}
@Override
public void afterTextChanged(Editable s) {}
});
}
我认为,我的逻辑也是错误的,因为当我输入单个输入并检查s.length
时,并且在et.setText("0")
之后,它将进入无限循环。
答案 0 :(得分:1)
尝试一下:
etAmount.addTextChangedListener(new 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 s) {
String text = s.toString();
if (text.length() == 2 && text.charAt(0) == '0') {
etAmount.setText(text.substring(1));
etAmount.setSelection(1);
}
}
});
答案 1 :(得分:0)
您可以这样做:
etAmount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int) {}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 2) {
if (s.toString().startsWith("00")) {
etAmount.setText("0");
}
}
}
});