Search code examples
androidcountdowntimer

How to make a countdown with seconds and milliseconds


I'm working with android studio to an app that have a countdown that starts from 10 seconds. I wrote the code and it works fine but it shows only the seconds remaining, now i want the countdown show the milliseconds too. Can you help me please? Here's the code

public class MainActivity extends Activity {
TextView txtCount;
Button btnCount;
int count = 0;


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

    txtCount = (TextView)findViewById(R.id.textView1);
    txtCount.setText(String.valueOf(count));
    btnCount = (Button)findViewById(R.id.button1);

    btnCount.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            count++;
            txtCount.setText(String.valueOf(count));
        }
    });
    final TextView textic = (TextView) findViewById(R.id.textView2);

    CountDownTimer Count = new CountDownTimer(10000, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) ((millisUntilFinished / 1000));

            textic.setText(seconds + "seconds " + millisUntilFinished / 1000);

        }

        public void onFinish() {
            textic.setText("TEMPO SCADUTO");
        }
    };

    Count.start();



}

Solution

  • Use remainder operator,

    millisUntilFinished % 1000
    

    Write something on the lines of

    textic.setText(seconds + "seconds " + millisUntilFinished / 1000 + " ms" + 
    millisUntilFinished / 1000);
    

    Although in your case, it will always return a 0 since your timer is ticking every 1000 milliseconds. To get a better picture, experiment with smaller ticker time values like 100 ms or 250 ms.

    CountDownTimer Count = new CountDownTimer(10000, 100){...