我已经知道,每次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;
            }


        }

    };

}

最佳答案

您将在此处获得NumberFormatExceptionuser_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;
}

08-04 16:06