MainActivity例如以下:
main.xml例如以下:
package cc.cv;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
/**
* Demo演示样例:
* CountDownTimer完整具体演示样例
* 代码非常easy,直接看凝视就可以
*
* CountDownTimer是Android4.0引入的倒计时
*/
public class MainActivity extends Activity {
private Button mStartButton;
private Button mCancelButton;
private CountDownTimerSubClass mCountDownTimerSubClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init(){
mCountDownTimerSubClass=new CountDownTimerSubClass(15*1000, 1000);
mStartButton=(Button) findViewById(R.id.startButton);
//開始倒计时
mStartButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mCountDownTimerSubClass.start();
}
});
//取消倒计时.
//再次调用CountDownTimer的start时会又一次開始倒计时.
mCancelButton=(Button) findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mCountDownTimerSubClass.cancel();
}
});
}
private class CountDownTimerSubClass extends CountDownTimer{
/**
* millisInFuture 倒计时间
* countDownInterval 每两次倒计时之间的间隔
*/
public CountDownTimerSubClass(long millisInFuture,long countDownInterval) {
super(millisInFuture, countDownInterval);
}
/**
* 倒计时结束
*/
@Override
public void onFinish() {
System.out.println("结束");
}
/**
* 每个倒计时间点到来时均会触发该方法
* millisUntilFinished表示整个倒计时剩余的时间
*/
@Override
public void onTick(long millisUntilFinished) {
long remainedSeconds=millisUntilFinished/1000;
System.out.println("剩余: "+remainedSeconds+" s");
}
}
}
main.xml例如以下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="start" />
<Button
android:id="@+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/startButton"
android:layout_marginTop="100dp"
android:text="cancel" />
</RelativeLayout>