Android 抢购类倒计时实现 (包括天数,小时,分钟,秒)

Android 抢购类倒计时实现,本文注重实现功能,代码里有注释,实现起来比较简单,所有不做过多解释。

先上图:

Android 抢购类倒计时实现 (包括天数,小时,分钟,秒)_第1张图片

实现倒计时可采用Message + Handler 来实现,具体实现如下:

MainActivity的代码如下:

package com.example.android_countdown;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 抢购倒计时
 * 
 * @author shihao
 * 
 */
public class MainActivity extends Activity {

	private RelativeLayout countDown;
	// 倒计时
	private TextView daysTv, hoursTv, minutesTv, secondsTv;
	private long mDay = 10;
	private long mHour = 10;
	private long mMin = 30;
	private long mSecond = 00;// 天 ,小时,分钟,秒
	private boolean isRun = true;
	private Handler timeHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what==1) {
				computeTime();
				daysTv.setText(mDay+"");
				hoursTv.setText(mHour+"");
				minutesTv.setText(mMin+"");
				secondsTv.setText(mSecond+"");
				if (mDay==0&&mHour==0&&mMin==0&&mSecond==0) {
					countDown.setVisibility(View.GONE);
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		countDown = (RelativeLayout) findViewById(R.id.countdown_layout);
		daysTv = (TextView) findViewById(R.id.days_tv);
		hoursTv = (TextView) findViewById(R.id.hours_tv);
		minutesTv = (TextView) findViewById(R.id.minutes_tv);
		secondsTv = (TextView) findViewById(R.id.seconds_tv);

		startRun();				
	}
	
	/**
	 * 开启倒计时 
	 */
	private void startRun() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (isRun) {
					try {
						Thread.sleep(1000); // sleep 1000ms
						Message message = Message.obtain();
						message.what = 1;
						timeHandler.sendMessage(message);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 倒计时计算
	 */
	private void computeTime() {
		mSecond--;
		if (mSecond < 0) {
			mMin--;
			mSecond = 59;
			if (mMin < 0) {
				mMin = 59;
				mHour--;
				if (mHour < 0) {
					// 倒计时结束
					mHour = 23;
					mDay--;
				}
			}
		}
	}
}

activity_main.xml代码如下:



    

        

        

        

        
    

    

        

        

        

        

        
    


项目下载地址:http://download.csdn.net/detail/shr957250701/8172137

你可能感兴趣的:(Android)