Count Down Timer Example

In this sample application we will create a countdown timer in android using the CountDownTimer class .This is an example of showing a 30 second countdown in a TextView . We will update the TextView on every tick of the timer.The option to stop and restart the timer is also provided.

activity_timer.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/bgi" > 
  
<TextView
android:id="@+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:paddingRight="10dip"
android:textSize="50dp" /> 
  
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Start" /> 
  
</RelativeLayout>

 

TimerActivity

public class TimerActivity extends Activity implements OnClickListener { 
  
 private CountDownTimer countDownTimer; 
 private boolean timerHasStarted = false; 
 private Button startB; 
 public TextView text; 
 private final long startTime = 30 * 1000; 
 private final long interval = 1 * 1000; 
  
 @Override 
 public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_timer); 
  startB = (Button) this.findViewById(R.id.button); 
  startB.setOnClickListener(this); 
  text = (TextView) this.findViewById(R.id.timer); 
  countDownTimer = new MyCountDownTimer(startTime, interval); 
  text.setText(text.getText() + String.valueOf(startTime / 1000)); 
 } 
  
 @Override 
 public void onClick(View v) { 
  if (!timerHasStarted) { 
   countDownTimer.start(); 
   timerHasStarted = true; 
   startB.setText("STOP"); 
  } else { 
   countDownTimer.cancel(); 
   timerHasStarted = false; 
   startB.setText("RESTART"); 
  } 
 } 
  
 public class MyCountDownTimer extends CountDownTimer { 
  public MyCountDownTimer(long startTime, long interval) { 
   super(startTime, interval); 
  } 
  
  @Override 
  public void onFinish() { 
   text.setText("Time's up!"); 
  } 
  
  @Override 
  public void onTick(long millisUntilFinished) { 
   text.setText("" + millisUntilFinished / 1000); 
  } 
 } 
  
}

 

태그: 
youngdeok의 이미지

Language

Get in touch with us

"어떤 것을 완전히 알려거든 그것을 다른 이에게 가르쳐라."
- Tryon Edwards -