本篇文章給大家分享的是有關(guān)怎么在Android中實(shí)現(xiàn)一個(gè)倒計(jì)時(shí)功能,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

以30分鐘為例寫的一個(gè)倒計(jì)時(shí):
public class MainActivity extends AppCompatActivity {
private int minute = 30;//這是分鐘
private int second = 0;//這是分鐘后面的秒數(shù)。這里是以30分鐘為例的,所以,minute是30,second是0
private TextView timeView;
private Timer timer;
private TimerTask timerTask;
//這是接收回來處理的消息
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (minute == 0) {
if (second == 0) {
timeView.setText("Time out !");
if (timer != null) {
timer.cancel();
timer = null;
}
if (timerTask != null) {
timerTask = null;
}
} else {
second--;
if (second >= 10) {
timeView.setText("0" + minute + ":" + second);
} else {
timeView.setText("0" + minute + ":0" + second);
}
}
} else {
if (second == 0) {
second = 59;
minute--;
if (minute >= 10) {
timeView.setText(minute + ":" + second);
} else {
timeView.setText("0" + minute + ":" + second);
}
} else {
second--;
if (second >= 10) {
if (minute >= 10) {
timeView.setText(minute + ":" + second);
} else {
timeView.setText("0" + minute + ":" + second);
}
} else {
if (minute >= 10) {
timeView.setText(minute + ":0" + second);
} else {
timeView.setText("0" + minute + ":0" + second);
}
}
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeView = (TextView) findViewById(R.id.tv);
timeView.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();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onPause() {
super.onPause();
}
}
網(wǎng)站欄目:怎么在Android中實(shí)現(xiàn)一個(gè)倒計(jì)時(shí)功能-創(chuàng)新互聯(lián)
本文鏈接:http://www.yijiale78.com/article12/ddcjdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、服務(wù)器托管、定制開發(fā)、網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站、建站公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容