本篇文章给大家分享的是有关怎么在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。