Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

How To Create A Timer in Android Application

instruction materials in android programming

Uploaded by

Amber Green
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

How To Create A Timer in Android Application

instruction materials in android programming

Uploaded by

Amber Green
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Create a new project with the following design in it

Textview Important to set the value into 120 if you want your timer to count 1
Progressbar minute and 30 seconds.

Button

TAKE NOTE:
TextView’s ID are lblTimer, txtTimer
Progress Bar ID is proBar
Button ID is btnStart

Open MainActivity.java and add the following code

package com.example.timer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class MainActivity extends AppCompatActivity {


TextView txtT;
ProgressBar progressBar;
Button btnStart;
private int mProgressStatus = 120;
//120 is equivalent to 1 minute and 30 seconds as maximum amount of the progress bar

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

txtT = findViewById (R.id.txtTimer);


progressBar = findViewById(R.id.proBar);
btnStart = findViewById(R.id.btnStart);

progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
progressBar.setProgress(mProgressStatus);

btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//120000 milliseconds is equivalent to 1 minute and 30 seconds
//1000 is equivalent to 1 second per tick of the clock
new CountDownTimer(120000, 1000){
public void onTick(long millisUntilFinished){
// Used for formatting digit to be in 2 digits only
NumberFormat f = new DecimalFormat("00");
long hour = (millisUntilFinished / 3600000) % 24;
long min = (millisUntilFinished / 60000) % 60;
long sec = (millisUntilFinished / 1000) % 60;
txtT.setText(f.format(hour) + ":" + f.format(min) + ":" +
f.format(sec));

mProgressStatus = progressBar.getProgress() - 1;
progressBar.setProgress(mProgressStatus);
}
// When the task is over it will print 00:00:00 there
public void onFinish(){
txtT.setText("GAME OVER!");
}
}.start();
}
});
}
}

You might also like