Android使用CountDownTimer倒计时

Android倒计时功能实现
本文详细介绍了一种在Android应用中实现倒计时功能的方法。包括布局文件的配置、倒计时逻辑的实现及线程控制等内容。适用于希望在Android项目中加入倒计时功能的开发者。

直接代码

1、布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>

2、调用

package com.best.daojishi;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
	CountdownUtil c;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView textView = (TextView) findViewById(R.id.textView1);

		c = new CountdownUtil(60000000, textView);
		c.countdown();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		c.stopThread();
	}
}

3、倒计时

package com.best.daojishi;

import java.text.SimpleDateFormat;
import java.util.TimeZone;
import android.os.CountDownTimer;
import android.widget.TextView;
/**
 * 倒计时
 * */
public class CountdownUtil {
	private long time;
	TextView counetdownView;
	CountdownThread thread;
	SimpleDateFormat formatter;
	String hms;
	/**
	 * @time:时间差(指定的一段时间长),时间戳
	 * @counetdownView:TextView显示倒计时
	 * */
	public CountdownUtil(long time, TextView counetdownView) {
		this.time = time;
		this.counetdownView = counetdownView;
	}
	/**
	 * 倒计时
	 * */
	public void countdown(){
		formatter = new SimpleDateFormat("HH:mm:ss");// 初始化Formatter的转换格式。
		formatter.setTimeZone(TimeZone.getTimeZone("GMT +8:00"));//设置时区(北京),如果你不设置这个,你会发现你的时间总会多出来8个小时

		thread = new CountdownThread(time, 1000);// 构造CountDownTimer对象
		thread.start();
	}
	class CountdownThread extends CountDownTimer {
		public CountdownThread(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
			// TODO Auto-generated constructor stub
		}
		@Override
		public void onTick(long millisUntilFinished) {
			hms = formatter.format(millisUntilFinished);//转化成  "00:00:00"的格式
			counetdownView.setText(hms);
		}

		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			//倒计时结束时触发
			counetdownView.setText("00:00:00");
		}
	}
	/**
	 * 终止线程
	 * */
	public void stopThread(){
		thread.cancel();
	}
}


转载于:https://my.oschina.net/Jieth/blog/469342

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值