本文就是 一个 CountDownTimer 的最简单的例子; 方便移植
不多说,上代码。
// SampleActivity.java
package com.yline.countdowntimer;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SampleActivity extends Activity implements OnClickListener {
TextView tv_time;
Button btn_start;
Button btn_stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_time = (TextView)findViewById(R.id.tv_time);
btn_start = (Button)findViewById(R.id.btn_start);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_start.setOnClickListener(this);
btn_stop.setOnClickListener(this);
}
/**
* 总共 40000 ms
* 每一跳,减少 1000 ms
*/
CountDownTimer timer = new CountDownTimer(40000,1000) {
@Override
public void onTick(long millisUntilFinished) {
tv_time.setText("seconds remaining: " + millisUntilFinished + " ms");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onFinish() {
tv_time.setText("done!");
}
};
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_start:
timer.start();
break;
case R.id.btn_stop:
timer.cancel();
break;
}
}
}
// activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="start" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/btn_start"
android:text="stop" />
<TextView
android:id="@+id/tv_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btn_start"
android:text="time" />
</RelativeLayout>
运行图:
本文可运行代码下载:
http://pan.baidu.com/s/1mg4zopU