我正在使用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.
}
});
答案 0 :(得分:2)
在afterTextChanged方法中......如果要看块是否为空。而不是使用输入编辑框使用您在方法参数中的可编辑的。
if (s.toString()!=null && s.toString().trim().equals("")==false){
double value=Double.parseDouble(s.getText().toString());
}else{
double value = 0;
}
答案 1 :(得分:0)
您可以这样做:
@Override
public void afterTextChanged(Editable s) {
try {
double value=Double.parseDouble(s.toString());
... //if there is something to do with value
} catch (NumberFormatException e) {
s.clear();
s.insert(0, "0");
// The method will be recalled since s was changed
}
}