Android Quiz Game - Countdown timer for each qstion

后端 未结 1 1079
北荒
北荒 2021-02-04 22:16

I have created a Quiz app for Android using the tutorial here: http://automateddeveloper.blogspot.co.uk/2011/06/getting-started-complete-android-app.html

For each questi

相关标签:
1条回答
  • 2021-02-04 22:44

    I think the activity doesn't exist anymore at a certain point when you try to make the dialog(probably when the CountDownTimer is near the end?!?).

    Anyway I think finishing and starting the same activity for each question isn't such a good idea, instead you could use the current activity and simply restart the timer. For example:

    public class QuestionActivity extends SherlockActivity implements
        OnClickListener {
    
       private CountDownTimer mCountDown;
    
       @Override
       public void onCreate(Bundle savedInstanceState) {
          // ...
          mCountDown = new CountDownTimer(20000, 1000) {
    
            @Override
            public void onFinish() {
                // myCounter.setText("Time up!");
                timeUp(context);
            }
    
            @Override
            public void onTick(long millisUntilFinished) {
                myCounter.setText("Time left: "
                        + String.valueOf(millisUntilFinished / 1000));
            }
          }.start();
          // ... 
    

    and in the onClick callback do the same to setup a new question, stop the old timer and restart the new timer:

    //check if end of game
    if (currentGame.isGameOver()) {
        Intent i = new Intent(this, EndgameActivity.class);
        startActivity(i);
        finish();
    } else {
        if (mCountDown != null) { 
           mCountDown.cancel();
        }  
        currentQ = currentGame.getNextQuestion();
        setQuestions();
        mCountDown = new CountDownTimer(20000, 1000) {
    
            @Override
            public void onFinish() {
                // myCounter.setText("Time up!");
                timeUp(context);
            }
    
            @Override
            public void onTick(long millisUntilFinished) {
                myCounter.setText("Time left: "
                        + String.valueOf(millisUntilFinished / 1000));
            }
        }.start();  
    }
    

    Also, in the callback for the Dialog's Button I would first close the Dialog before finishing the Activity:

    ((AlertDialog) dialog).dismiss();
    QuestionActivity.this.finish();
    
    0 讨论(0)
提交回复
热议问题