如何在用户单击按钮后立即覆盖当前的EditText输入



在我的应用程序中,我有一个EditText,用户在其中键入问题的答案,然后点击ok按钮。当他的答案是正确的时,会有一个图像显示他回答正确。如果他的答案是错误的,那么他的答案就是错误的。我现在想要的是,当用户回答错误时,他可以键入另一个答案,所以我需要一个功能,当用户单击键盘上的任何按钮时,旧的编辑文本输入将被新的输入覆盖。我只是设法做到,当用户点击键盘上的任何按钮时,EditText都会被清除,但它不会被新输入覆盖。

有人有什么建议吗?我在这里没有找到任何答案。

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (!answered.equals("true")) {
// Add Text Watcher on name input text
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
wrongAnswer.setVisibility(View.INVISIBLE);
if (clearText) {
editText.getText().clear();
clearText = false;
}
}
@Override
public void afterTextChanged(Editable s) {
//This method prevents that the player types in a zero as first number
if (s.toString().length() == 1 && s.toString().startsWith("0")) {
s.clear();
}
}
});
}
}

希望这就是你所需要的:

Button.setOnClickListener(new View.OnClickListener { //set onclicklistener for button
@override
onClick() {
if (!answered.equals("true")) { //check if answer is wrong
editText.setText(""); //set text to empty
answerImage.setImageResource(R.drawable.wrong); //set image to wrong
}
}

希望这对你有帮助!快乐编码:(

单击按钮更改editText 的文本时,可以使用editText.setText("your new text")方法

最新更新