前言
每次需要寫倒計時都會寫很多不想寫的代碼,去以前的代碼復制粘貼有麻煩莉钙,還不如寫在網絡上陕壹,需要的時候直接打開復制下來就行了
private int minute = 1;//這是分鐘
private int second = 0;//這是分鐘后面的秒數。這里是以30分鐘為例的浸剩,所以可帽,minute是30娄涩,second是0
private TextView tvname;
private Timer timer;
private TimerTask timerTask;
//這是接收回來處理的消息
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (minute == 0) {
if (second == 0) {
tvname.setText("結束");
if (timer != null) {
timer.cancel();
timer = null;
}
if (timerTask != null) {
timerTask = null;
}
} else {
second--;
if (second >= 10) {
tvname.setText("0" + minute + ":" + second);
} else {
tvname.setText("0" + minute + ":0" + second);
}
}
} else {
if (second == 0) {
second = 59;
minute--;
if (minute >= 10) {
tvname.setText(minute + ":" + second);
} else {
tvname.setText("0" + minute + ":" + second);
}
} else {
second--;
if (second >= 10) {
if (minute >= 10) {
tvname.setText(minute + ":" + second);
} else {
tvname.setText("0" + minute + ":" + second);
}
} else {
if (minute >= 10) {
tvname.setText(minute + ":0" + second);
} else {
tvname.setText("0" + minute + ":0" + second);
}
}
}
}
}
};
//在oncreate中
tvname = (TextView) findViewById(R.id.tvname);
if (minute == 0 && second == 30) {
tvname.setText("" + minute + ":" + second);
tvname.setTextColor(getResources().getColor(R.color.red));
} else {
tvname.setText(minute + ":" + second);
}
timerTask = new TimerTask() {
@Override
public void run() {
Message msg = new Message();
msg.what = 0;
handler.sendMessage(msg);
}
};
timer = new Timer();
timer.schedule(timerTask, 0, 1000);
}
@Override
protected void onDestroy() {
if (timer != null) {
timer.cancel();
timer = null;
}
if (timerTask != null) {
timerTask = null;
}
minute = -1;
second = -1;
super.onDestroy();
}