我有一个编辑文本来填充金额。所以,我添加了文本观察器,但我不希望用户“0000000 ...”如果用户将连续按“0000 ...”而不是它应该只显示一次“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")
之后,它将进入无限循环。
试试这个:
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);
}
}
});
你可以这样做:
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");
}
}
}
});