`
苹果超人
  • 浏览: 195859 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

AnalogClock和DigitalClock

阅读更多
  本篇主要介绍一下AnalogClock和DigitalClock控件。
package com.kevin.clock;

import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.AnalogClock;
import android.widget.DigitalClock;
import android.widget.TextView;

public class Main extends Activity {
	private static final int MSGTYPE = 1;
	private AnalogClock analogClock;
	private TextView tv_title;
	private DigitalClock digitalClock;
	private Calendar calendar;
	private int hour;
	private int minute;
	private int second;
	private Handler handler;
	private Thread thread;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tv_title = (TextView) findViewById(R.id.tv_title);
		analogClock = (AnalogClock) findViewById(R.id.analogClock1);
		digitalClock = (DigitalClock) findViewById(R.id.digitalClock1);
		// 通过Handler来接受线程锁传递的信息并更新TextView
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSGTYPE:
					tv_title.setText(hour + ":" + minute + ":" + second);
					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
		// 每隔一秒取得系统时间
		thread = new LooperThread();
		thread.start();
	}

	class LooperThread extends Thread {
		@Override
		public void run() {
			try {
				while (true) {
					// 取得系统时间
					long time = System.currentTimeMillis();
					calendar = Calendar.getInstance();
					calendar.setTimeInMillis(time);
					second = calendar.get(Calendar.SECOND);
					minute = calendar.get(Calendar.MINUTE);
					hour = calendar.get(Calendar.HOUR_OF_DAY);
					Thread.sleep(1000);
					Message msg = new Message();
					msg.what = MSGTYPE;
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics