- Back to Home »
- Android »
- How to write a countdown timer (CountDownTimer)
Tuesday, June 26, 2012
Write a countdown timer is actually very simple, there is a category on the official website
The called CountDownTimer can be directly used to take over.
This is over the paste from the official website
http://developer.android.com/reference/android/os/CountDownTimer.html
Direct new CountDownTimer this category, it will pass in two parameters,
The first parameter is the total of timing a few seconds, 0.001 for 30 seconds countdown, so it is necessary to multiply 30 * 1000,
The second parameter is every few seconds to jump to 0.001 as a unit, every other second jump is passed in 1000.
Must override two methods is a Finish () a onTick (), when every jump you pass the second parameter the number of seconds when
Will jump into onTick this method once, and when the number of seconds that the sum of the first parameter,
This count is over, it will jump into this method of Finish.
So we each jump of the second, it will be the number of seconds to present
When the end of the countdown will show Done!
The called CountDownTimer can be directly used to take over.
The code is very simple
public class CountdownTimerDemoActivity extends Activity { /** Called when the activity is first created. */ private TextView mTextView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView)findViewById(R.id.text_view); new CountDownTimer(30000,1000){ @Override public void onFinish() { // TODO Auto-generated method stub mTextView.setText("Done!"); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub mTextView.setText("seconds remaining:"+millisUntilFinished/1000); } }.start(); } }
This is over the paste from the official website
http://developer.android.com/reference/android/os/CountDownTimer.html
Direct new CountDownTimer this category, it will pass in two parameters,
The first parameter is the total of timing a few seconds, 0.001 for 30 seconds countdown, so it is necessary to multiply 30 * 1000,
The second parameter is every few seconds to jump to 0.001 as a unit, every other second jump is passed in 1000.
Must override two methods is a Finish () a onTick (), when every jump you pass the second parameter the number of seconds when
Will jump into onTick this method once, and when the number of seconds that the sum of the first parameter,
This count is over, it will jump into this method of Finish.
So we each jump of the second, it will be the number of seconds to present
When the end of the countdown will show Done!
Code