[英]Why doesn't the text on my buttons update in my Android App?
所以我正在 Android Studio 中開發一個應用程序。
在這個開發階段,我的應用程序似乎運行良好,除了按鈕中文本的更新。
我的應用程序的代碼應該更新我的按鈕上的文本如下。
private void selectedAnswer(int answerSelection) {
Question currentQuestion = selectQuestion();
answer0button.setText(currentQuestion.answer0);
answer1button.setText(currentQuestion.answer1);
answer2button.setText(currentQuestion.answer2);
answer3button.setText(currentQuestion.answer3);
if (answerSelection == 0) {
if (answerSelection == currentQuestion.correctAnswer - 1) {
answer0button.setText(currentQuestion.answer0 + " ✔");
addPoints();
}
else {
answer0button.setText(currentQuestion.answer0 + " ✗");
}
}
else if (answerSelection == 1) {
if (answerSelection == currentQuestion.correctAnswer - 1) {
answer1button.setText(currentQuestion.answer1 + " ✔");
addPoints();
}
else {
answer1button.setText(currentQuestion.answer1 + " ✗");
}
}
else if (answerSelection == 2) {
if (answerSelection == currentQuestion.correctAnswer - 1) {
answer2button.setText(currentQuestion.answer2 + " ✔");
addPoints();
}
else {
answer2button.setText(currentQuestion.answer2 + " ✗");
}
}
else if (answerSelection == 3) {
if (answerSelection == currentQuestion.correctAnswer - 1) {
answer3button.setText(currentQuestion.answer3 + " ✔");
addPoints();
}
else {
answer3button.setText(currentQuestion.answer3 + " ✗");
}
}
nextQuestion();
}
但是,nextQuesiton() 行會阻止文本正確更新。 如果沒有這一行,代碼將按預期工作。
問題中的行執行以下方法。
private void nextQuestion(){
gameRound += 1;
displayQuestion(selectQuestion());
}
這個方法反過來執行這個方法。
private void displayQuestion(Question question){
questionTextView.setText(question.questionText);
answer0button.setText(question.answer0);
answer1button.setText(question.answer1);
answer2button.setText(question.answer2);
answer3button.setText(question.answer3);
}
似乎 selectedAnswer() 方法和 displayQuestion() 方法中的行可能同時執行,但 displayQuestion() 方法覆蓋了 selectedAnswer() 中的行。
任何人都可以告訴我到底是什么導致了我的問題,以及如何解決它。
我認為您的代碼沒有任何問題,但是按鈕的更新發生得太快了,它會在您甚至意識到之前已更改為另一個文本之前更改為第二個文本。 我認為,對於所需的行為,您應該實現一個異步調用,在幾毫秒后執行“nextQuestion”。
就像是:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
nextQuestion();
}
}, 1000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.