========转载自http://blog.csdn.net/flyxman============
package com.example.timertextviewdemo;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class TimerTextView extends TextView implements Runnable {
// 时间变量
private int day, hour, minute, second;
// 当前计时器是否运行
private boolean isRun = false;
public TimerTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public TimerTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimerTextView(Context context) {
super(context);
}
/**
* 将倒计时时间毫秒数转换为自身变量
*
* @param time
* 时间间隔毫秒数
*/
public void setTimes(long time) {
//将毫秒数转化为时间
this.second = (int) (time / 1000) % 60;
this.minute = (int) (time / (60 * 1000) % 60);
this.hour = (int) (time / (60 * 60 * 1000) % 24);
this.day = (int) (time / (24 * 60 * 60 * 1000));
}
/**
* 显示当前时间
*
* @return
*/
public String showTime() {
StringBuilder time = new StringBuilder();
time.append(day);
time.append("天");
time.append(hour);
time.append("小时");
time.append(minute);
time.append("分钟");
time.append(second);
time.append("秒");
return time.toString();
}
/**
* 实现倒计时
*/
private void countdown() {
if (second == 0) {
if (minute == 0) {
if (hour == 0) {
if (day == 0) {
//当时间归零时停止倒计时
isRun = false;
return;
} else {
day--;
}
hour = 23;
} else {
hour--;
}
minute = 59;
} else {
minute--;
}
second = 60;
}
second--;
}
public boolean isRun() {
return isRun;
}
/**
* 开始计时
*/
public void start() {
isRun = true;
run();
}
/**
* 结束计时
*/
public void stop() {
isRun = false;
}
/**
* 实现计时循环
*/
@Override
public void run() {
if (isRun) {
// Log.d(TAG, "Run");
countdown();
this.setText(showTime());
postDelayed(this, 1000);
} else {
removeCallbacks(this);
}
}
}
调用==========================
package com.example.timertextviewdemo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
/**
* http://blog.csdn.net/flyxman
* @author flyxman
*/
public class MainActivity extends Activity {
private TimerTextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
//获得当前时间
Date now = new Date();
//目标时间
Date target = null;
try {
target = dateFormat.parse("2015/6/22 11:37:00");
} catch (ParseException e) {
e.printStackTrace();
}
//获得时间差
long diff = target.getTime() - now.getTime();
mTextView = (TimerTextView) findViewById(R.id.timerTextView);
//设置时间
mTextView.setTimes(diff);
/**
* 开始倒计时
*/
if(!mTextView.isRun()){
mTextView.start();
}
}
}