我发现每次afterTextChanged()
文本更改时都会调用EditText
(这就是它崩溃的原因),但我不知道如何解决问题。有谁可以帮助我!
设置修改文字并添加addTextChangedListener
editText= (EditText) findViewById(R.id.editText);
editText.setInputType(InputType.TYPE_NULL);
editText.addTextChangedListener(textWatcher);
textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//editText.removeTextChangedListener(textWatcher); //this doesn't help
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
// Toast.makeText(mainAct, "OK",Toast.LENGTH_SHORT).show();
String user_answer =editText.getText().toString();
user_ans_int = Integer.parseInt(user_answer);
这应该检查EditText
中的文本是否正确,这也是应用程序崩溃的地方(没有这部分它运行完美)
if (user_ans_int == answer){
Toast.makeText(mainAct, "True", Toast.LENGTH_SHORT).show();
editText.setText("");
}
else {
Toast.makeText(mainAct, "Naaw - try again haha", Toast.LENGTH_SHORT).show();
editText.setText("");//delete text after checking
tru = false;
}
}
};
}
答案 0 :(得分:2)
您将在此处获得NumberFormatException
:user_ans_int = Integer.parseInt(user_answer);
这是因为您为editText
签署了无号码值并导致其afterTextChanged()
被调用。
我认为您可以按以下方式更改代码:
user_ans_int = Integer.parseInt(user_answer);
为:
try{
user_ans_int = Integer.parseInt(user_answer);
}catch(NumberFormatException e){
// A none number value is signed to your edittext, do something here.
return;
}
答案 1 :(得分:1)
更新if..else语句中的文本时,需要禁用TextWatcher,以检查答案是否正确。你现在做的是检查答案是否正确,然后将文本设置回""。这再次触发了文本观察者,因为文本已经改变。然后你尝试解析为一个空字符串int。所以将你的if..else更改为:
if (user_ans_int == answer){
editText.removeTextChangedListener(textWatcher);
Toast.makeText(mainAct, "True", Toast.LENGTH_SHORT).show();
editText.setText("");
editText.addTextChangedListener(textWatcher);
} else {
editText.removeTextChangedListener(textWatcher);
Toast.makeText(mainAct, "Naaw - try again haha", Toast.LENGTH_SHORT).show();
editText.setText("");//delete text after checking
tru = false;
editText.addTextChangedListener(textWatcher);
}
实际上,您还可以放置一个try..catch语句,将editText的内容解析为int以捕获异常,但在这种情况下,您将调用textWatcher而无需执行此操作。我相信禁用和重新启用textWatcher会更有效率。
答案 2 :(得分:0)
// Write down few code inside a afterTextChanged method
if(!s.equal("")){
try {
String user_answer = s.getText().toString();
user_ans_int = Integer.parseInt(user_answer);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}else{
Toast.makeText(mainAct, "Please Enter Text",Toast.LENGTH_SHORT).show();
}