0

我正在编写一个测验应用程序,它向用户提供一个问题和 4 个选择。当用户单击一个选项时,应用程序应将正确选项的颜色更改为绿色,将错误选项的颜色更改为红色。然后它应该在显示下一个问题之前等待一秒钟。

问题是它不会改变颜色(最后一个问题除外),我不明白为什么。我知道我android.os.SystemClock.sleep(1000)和它有关系。

如果您能告诉我哪里出了问题,或者我的做法不正确,我将不胜感激。谢谢 :)

public void onClick(View v) {
    setButtonsEnabled(false);
    int answer = Integer.parseInt(v.getTag().toString());
    int correct = question.getCorrectAnswer();

    if(answer == correct)
        numCorrect++;
    highlightAnswer(answer,correct,false);
    android.os.SystemClock.sleep(1000);

    MCQuestion next = getRandomQuestion();
    if(next != null) {
        question = next;
        highlightAnswer(answer,correct,true);
        displayQuestion();
        setButtonsEnabled(true);
    }
    else {
        float percentage = 100*(numCorrect/questionsList.size());
        QuizTimeApplication.setScore(percentage);
        Intent scoreIntent = new Intent(QuestionActivity.this,ScoreActivity.class);
        startActivity(scoreIntent);
    }
}

private void setButtonsEnabled(boolean enable) {
    for(Button b: buttons)
        b.setEnabled(enable);
}

private void highlightAnswer(int answer, int correct, boolean undo) {
    if(undo) {
        for(Button button : buttons) {
            button.setTextColor(getResources().getColor(R.color.white));
            button.setTextSize(FONT_SIZE_NORMAL);
        }
        return;
    }
    buttons[correct].setTextColor(getResources().getColor(R.color.green));
    buttons[correct].setTextSize(FONT_SIZE_BIG);
    if(answer!=correct) {
        buttons[answer].setTextColor(getResources().getColor(R.color.red));
        buttons[answer].setTextSize(FONT_SIZE_BIG);
    }
}
4

1 回答 1

3
SystemClock.sleep(1000);

会产生意想不到的行为,并且可能无法满足您的要求。最好使用 Handler 延迟如下。

Handler h = new Handler();
h.postDelayed(new Runnable(){

@Override
public void run()
{
//your code that has to be run after a delay of time. in your case the code after SystemClock.sleep(1000);
},YOUR_DELAY_IN_MILLISECONDS
);
于 2012-12-24T12:34:58.937 回答