我有一个 EditText
和一个 TextWatcher
。
我正在其中输入数字,如果最后一个文本被删除,我想用 0 填充该字段。
如何使用TextWatcher
的三种方法?
input.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
double value=Double.parseDouble(input.getText().toString());//here it will throw error if no text there.
//I do not only want to catch this exception and do something with it, but I want to detect this event and if it happens I want to try some solution to stop it.
}
});
最佳答案
在 afterTextChanged 方法中...放入 if block 以查看它是否为空。另外,不要使用输入编辑框,而是使用方法参数中的 Editable 。
if (s.toString()!=null && s.toString().trim().equals("")==false){
double value=Double.parseDouble(s.getText().toString());
}else{
double value = 0;
}
关于android - 使用 TextWatcher 检测最后删除的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26154651/