16

I want to display the timer in TextView in the format of like [ 19:59].so when i click the start button ,the timer will display like this for example,i want to set upto 20 mintues,it will display like [19:58][19:87].can anyone give some ideas or example code?enter image description here

rajeshlawrance
  • 549
  • 2
  • 6
  • 25

8 Answers8

25

You can use the CountDownTimer.

http://developer.android.com/reference/android/os/CountDownTimer.html

     TextView _tv = (TextView) findViewById( R.id.textView1 );
    new CountDownTimer(20*60000, 1000) {

        public void onTick(long millisUntilFinished) {
            _tv.setText("seconds remaining: " +new SimpleDateFormat("mm:ss:SS").format(new Date( millisUntilFinished)));
        }

        public void onFinish() {
           _tv.setText("done!");
        }
     }.start();

To cancel just call cancel on the timer.

public final void cancel()

Cancel the countdown.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
17
package com.example.testproject;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

    public int seconds = 60;
    public int minutes = 10;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Declare the timer
        Timer t = new Timer();
        //Set the schedule function and rate
        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        TextView tv = (TextView) findViewById(R.id.main_timer_text);
                        tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
                        seconds -= 1;

                        if(seconds == 0)
                        {
                            tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));

                            seconds=60;
                            minutes=minutes-1;

                        }



                    }

                });
            }

        }, 0, 1000);
    }

}
rajeshlawrance
  • 549
  • 2
  • 6
  • 25
7

do it this way activity_timer.xml

<android.support.v7.widget.LinearLayoutCompat
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <Chronometer
            android:id="@+id/chronometer2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


    </android.support.v7.widget.LinearLayoutCompat>

And in Activity

public class TimerActivity extends AppCompatActivity {
   private Chronometer chronometer2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer);

        chronometer2 = findViewById(R.id.chronometer2);
        chronometer2.start();
    }
}

You can also use stop

chronometer2.stop();

Re Start

chronometer2.setBase(SystemClock.elapsedRealtime());
 chronometer2.start();
Tarun Umath
  • 900
  • 10
  • 7
6
  //start button click
     CountDown timer = new CountDown(180000, 1000);
     timer.start();

//stop button click
timer.stop();   

    //countdown class
    public class CountDown extends CountDownTimer {

          public CountDown(long millisInFuture, long countDownInterval) {
             super(millisInFuture, countDownInterval);
          }

          @Override
          public void onTick(long millisUntilFinished) {
             long ms = millisUntilFinished;
             String text = String.format("%02d\' %02d\"",
                                         TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
                                         TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
             textViewTimer.setText(text);
          }

          @Override
          public void onFinish() {
             textViewTimer.setText("ffinish");
          }
       }
msevgi
  • 4,828
  • 2
  • 24
  • 30
1

Here I have use Timer class to display timer

    public class FourthActivity extends AppCompatActivity {
    Button startButton, pauseButton;
    TextView timerValue;
    Timer timer;
    int seconds = 0, minutes = 0, hour = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fourth);
        bindView();

        timer = new Timer();
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (seconds == 60) {
                                    timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
                                    minutes = seconds / 60;
                                    seconds = seconds % 60;
                                    hour = minutes / 60;
                                }
                                seconds += 1;
                                timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
                            }
                        });
                    }
                }, 0, 1000);
            }
        });
    }

    private void bindView() {
        timerValue = (TextView) findViewById(R.id.timerValue);
        startButton = (Button) findViewById(R.id.startButton);
    }
}

In layout, there are one TextView and one Button to start timer. I have use Timer class method scheduleAtFixedRate. Time will be displayed in hh:mm:ss form.

Apurva Kolapkar
  • 1,270
  • 2
  • 16
  • 32
Khyati Vara
  • 1,042
  • 13
  • 22
  • 1
    not correct, minutes can not increase more than 1. you should ++ it in if statement, same problem for hours – Arash Jul 25 '18 at 07:22
1

Showing timer in Kotlin.

class TimerDemo : AppCompatActivity() {

private lateinit var binding: ActivityTimerDemoBinding
private lateinit var timer: Timer
private var seconds = 0
private var secondsToDisplay = 0
private var minutes = 0
private var hours = 0

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityTimerDemoBinding.inflate(layoutInflater)
    setContentView(binding.root)
    configureTimer()
}

private fun configureTimer() {
    timer = Timer().apply {
        scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    if (seconds % 60 == 0) {
                        binding.tvTimerValue.text =
                            "${String.format("%02d", hours)} :" +
                                    " ${String.format("%02d", minutes)} :" +
                                    " ${String.format("%02d", secondsToDisplay)}"
                        minutes = seconds / 60
                        secondsToDisplay %= 60;
                        hours = minutes / 60
                    }
                    seconds++
                    secondsToDisplay++
                    binding.tvTimerValue.text =
                        "${String.format("%02d", hours)} :" +
                                " ${String.format("%02d", minutes)} :" +
                                " ${String.format("%02d", secondsToDisplay)}"
                }
            }
        }, 0, 1000)
    }
}

override fun onStart() {
    super.onStart()
    binding.btnStopTimer.setOnClickListener { timer.cancel() }
}

}
Raj Kanchan
  • 450
  • 6
  • 11
0

This can be done using cronometer, the most main reason is supporting API 1+, which is quite impressive rather than TextClock, which supports API 17+.

You can do lots of other things with cronometer. for example you can set start time in it

chronometer.setBase(SystemClock.elapsedRealtime());

You can also learn about it more here.

Mayank Sharma
  • 739
  • 8
  • 13
0

I made code for timer display in textView.The formate is for e.g:- 02:59:00

You can follow this link to get the Step By Step Code.

https://stackoverflow.com/a/58316149/11613683

Pramesh Bhalala
  • 273
  • 1
  • 3
  • 9