您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關怎么在Android中實現一個倒計時功能,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
以30分鐘為例寫的一個倒計時:
public class MainActivity extends AppCompatActivity {
private int minute = 30;//這是分鐘 private int second = 0;//這是分鐘后面的秒數。這里是以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中實現一個倒計時功能,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。