Android限时抢购倒计时控件源代码
程序员文章站
2022-02-14 11:20:41
...
最近在项目中使用到了抢购的活动、自然就会涉及到倒计时的功能、功能差不多已经完成了、现在分享一下Android实现计时器的代码、整个倒计时是用Timer来实现的、通过一个TimerTask和Handler实现的倒计的效果、希望对一些有相同需求的朋友有帮助、下面是Demo的效果图片
Handler代码
Handler handler = new Handler(){ public void handleMessage(Message msg) { System.out.println("handle!"); 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); } } } } }; };
onCreate初始化
@Override protected void onCreate(Bundle savedInstanceState) { Log.v(tag, "log---------->onCreate!"); requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.start); timeView = (TextView)findViewById(R.id.myTime); if (minute == -1 && second == -1) { Intent intent = getIntent(); ArrayList<Integer> times = intent.getIntegerArrayListExtra("times"); minute = times.get(0); second = times.get(1); } 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); }
android抢购倒计时源代码下载链接: android抢购倒计时器 密码: s7ty