您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(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(); } }
以上就是怎么在Android中實(shí)現(xiàn)一個(gè)倒計(jì)時(shí)功能,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。