清除 EditText 时应用崩溃

App crashes when clearing EditText

我正在制作这个试玩游戏,有人猜了一个数字后,需要清除 EditText 视图。

这是我的 onCreate:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    Button b = (Button) findViewById(R.id.check);
    final EditText input = (EditText) findViewById(R.id.number);
    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (!input.getText().toString().matches("")) {
                input.setText("");
                handleGuess(Integer.parseInt(input.getText().toString()));
            } else {
                Toast.makeText(getApplicationContext(), "Je hebt geen nummer ingevuld!", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
                if (!input.getText().toString().matches("")) {
                    input.setText("");
                    handleGuess(Integer.parseInt(input.getText().toString()));
                } else {
                    Toast.makeText(getApplicationContext(), "Je hebt geen nummer ingevuld!", Toast.LENGTH_SHORT)
                            .show();
                }
            }
            return false;
        }
    });
}

每当我尝试在软键盘上按 Enter 键或按下按钮时,它只会显示“RaadHetGetal stopped”。

有什么想法吗?需要看的就说吧

在你的两个听众中你至少有这个错误:

您将文本设置为空

input.setText("");

然后尝试直接从中解析一个 int。这导致 NumberFormatException

handleGuess(Integer.parseInt(input.getText().toString()));

所以如果想清除handleGuess之后的文字,可以调用clear().

handleGuess(Integer.parseInt(input.getText().toString()));
input.clear();

好的,您在第

行获得 java.lang.NumberFormatException
Integer.parseInt(input.getText().toString())

由于您使用以下代码行将 TextView 设置为空:

input.setText("");