简体   繁体   中英

How to implement CountDownTimer reducing time functionality in Android

I have a CountDownTimer implemented in my activity that runs and shows a timer of 15 min. I want to add a feature where, if the input entered by the user is incorrect, the time remaining on the clock is reduced by 20 seconds. The CountDownTimer is implemented as shown below:

//            counter = TimerClass.getInstance();
//            System.out.println("Timer: " + counter.getFormatedTime());
//            ((TextView) findViewById(R.id.time)).setText(counter.getFormatedTime());

            new CountDownTimer(Activity_Game.time, 1000){
                @Override
                public void onTick(long millisUntilFinished) {
                    Activity_Game.time = (int) millisUntilFinished;
                    Log.d(TAG, "onTick: "+Activity_Game.time);
                    millisUntilFinished = millisUntilFinished/1000;
                    ((TextView) findViewById(R.id.time)).setText(String.format("Time: %02d:%02d",
                            (millisUntilFinished % 3600) / 60, (millisUntilFinished % 60)) + "");
                    @Override
                public void onFinish() {
                    // Don't need to finish twice as activity game has timer ticking on the same time so 
                      it will finish this activity and pop up game over/vicotry

                }
            }.start();

        } catch (Exception exception) {
            exception.printStackTrace();
        }

I check whether the input matched my parameters in the following code:

 public void onClickSubmit(View view){

        //Get user entered text
        EditText ansText = findViewById(R.id.answerText);
        String userInput = ansText.getText().toString();

        //choice 4 ans contains comma
        //
        double RightansInDouble;
        double UseansInDouble;

        try {
            if (currentAnswer.contains(",")) {
//            RightansInDouble = Double.parseDouble(currentAnswer);
                UseansInDouble = Double.parseDouble(userInput);

                String[] ans = currentAnswer.split(",");
                double ans1 = Double.parseDouble(ans[0]);
                double ans2 = Double.parseDouble(ans[1]);

                //If the answer is right
                if (Math.abs(ans1 - UseansInDouble) <= 0.5 || Math.abs(ans2 - UseansInDouble) <= 0.5) {
                    //Do something
                    //Increment in points
                    TextView score = findViewById(R.id.Currentscore);
                    currentScore = Integer.parseInt(score.getText().toString());
                    currentScore+= 2;

                    activity_game.score+= 2;
                    score.setText(activity_game.score + "");

                    //new question to be displayed
                    nextQuestion();
                } else {
                    //if the use entered answer is incorrect
                    // go down a stage
//                    System.out.println("Wrong answer");
                    if(Activity_Game.score > 0)
                        Activity_Game.score-=2;
                    
                    Toast t = Toast.makeText(Activity_Room.this, "Wrong Answer! Try again!", Toast.LENGTH_SHORT);
                    t.show();
                }
            } else {
                RightansInDouble = Double.parseDouble(currentAnswer);
                UseansInDouble = Double.parseDouble(userInput);

                //If the answer is right
                if (Math.abs(RightansInDouble - UseansInDouble) <= 0.5) {
                    //Do something
                    //Increment in points
                    TextView score = findViewById(R.id.Currentscore);
                    currentScore+= 2;
                    activity_game.score+= 2;
                    score.setText(activity_game.score + "");

                    //new question to be displayed
                    nextQuestion();
                } else {
                    //if the use entered answer is incorrect
//                    System.out.println("Wrong answer");
                    if(Activity_Game.score > 0)
                        Activity_Game.score-=2;

                    Toast t = Toast.makeText(Activity_Room.this, "Wrong Answer! Try again!", Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        }
        catch (Exception e){
            Toast t = Toast.makeText( Activity_Room.this, "Invalid Input! Use only digits and points if necessary!", Toast.LENGTH_SHORT);
            t.show();
//            System.out.println("Invalid Input");
        }

        //for testing purpose
//        System.out.println("Clicked submit button");
//        nextQuestion();
    }

I am not sure on how to proceed on implementing a system where once a incorrect answer is detected, the timer clock is reduced by 20 seconds. Any help would be appreciated

Add a global variable that has a value of zero if the user input is correct, otherwise it has a value of 20. Use this variable in your timer's onTick() method to subtract it from the remaining time.

You can use this code working for me

private fun otpCountdown() {
            val countDownTimer = object : CountDownTimer(60000, 1000) {
                override fun onTick(p0: Long) {
                    val millis: Long = p0
                    val hms = String.format(
                        "%02d:%02d",
                        (TimeUnit.MILLISECONDS.toMinutes(millis) -
                                TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))),
                        (TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(
                            TimeUnit.MILLISECONDS.toMinutes(millis)
                        ))
                    )
                    textView?.text = hms;
                }
    
                override fun onFinish() {
                    textView?.text = "Resend";
                }
            }
            countDownTimer.start()
    
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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