简体   繁体   中英

Android CountDown Set Seconds to edittext

I can set only minutes on my countdown using edit text, how about it can set also seconds on edit text on the countdown timer, any help guys don't have any clue how to set seconds

public void onClick(View v) {
        switch (v.getId()) {
            case R.id.startTimer:
                //If CountDownTimer is null then start timer
                if (countDownTimer == null) {
                    String getMinutes = minutes.getText().toString();//Get minutes from edittexf
                    //Check validation over edittext
                    if (!getMinutes.equals("") && getMinutes.length() > 0) {
                        int noOfMinutes = Integer.parseInt(getMinutes) * 60 * 1000;//Convert minutes into milliseconds

                        startTimer(noOfMinutes);//start countdown
                        startTimer.setText(getString(R.string.stop_timer));//Change Text

                    } else
                        Toast.makeText(MainActivity.this, "Please enter no. of Minutes.", Toast.LENGTH_SHORT).show();//Display toast if edittext is empty
                } else {
                    //Else stop timer and change text
                    stopCountdown();
                    startTimer.setText(getString(R.string.start_timer));
                }
                break;
            case R.id.resetTimer:
                stopCountdown();//stop count down
                startTimer.setText(getString(R.string.start_timer));//Change text to Start Timer
                countdownTimerText.setText(getString(R.string.timer));//Change Timer text
                break;
        }


    }

You can try this to show minutes and seconds:

new CountDownTimer(90000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            String text = String.format(Locale.getDefault(), "Time Remaining %02d min: %02d sec", 
            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60, 
            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
            tvTime.setText(text);
        }
 });

Change the initialization of countDownTimer according to your needs

IMO, startTimer accepts milliseconds as its parameters. You cannot set the Timer in seconds there. But use this to show seconds:

startTimer.setText(Integer.parseInt(getString(R.string.stop_timer)) / 1000);

This shows the timer in Seconds.

Hope it helps.

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