繁体   English   中英

为什么我的 Android 应用程序中按钮上的文字没有更新?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM