標籤:
TimeView.java
package com.mytest.myclock;import java.util.Calendar;import android.content.Context;import android.opengl.Visibility;import android.os.Handler;import android.util.AttributeSet;import android.view.View;import android.widget.LinearLayout;import android.widget.TextView;public class TimeView extends LinearLayout { private TextView timeText; public TimeView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } public TimeView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public TimeView(Context context) { super(context); // TODO Auto-generated constructor stub } @Override protected void onFinishInflate() { // TODO Auto-generated method stub super.onFinishInflate(); timeText = (TextView) findViewById(R.id.tv_time); timeHandler.sendEmptyMessage(0); } private void refreshTime() { Calendar cal = Calendar.getInstance(); String timeStr = String.format("%d:%d:%d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); timeText.setText(timeStr); //System.out.println("timeStr============>" + timeStr); } @Override protected void onVisibilityChanged(View changedView, int visibility) { // TODO Auto-generated method stub super.onVisibilityChanged(changedView, visibility); if (getVisibility() == View.VISIBLE) { timeHandler.sendEmptyMessageDelayed(0, 1000); } else { timeHandler.removeMessages(0); } } private Handler timeHandler = new Handler() { public void handleMessage(android.os.Message msg) { refreshTime(); if (getVisibility() == View.VISIBLE) { // 每隔一秒給自己發送訊息 timeHandler.sendEmptyMessageDelayed(0, 1000); } }; };}View Code
小結:
1、在onFinishInflate中發送訊息,實現時間的第一次顯示。後來又在handler的handleMessage方法中發送訊息,有點相當於調用死迴圈來重新整理時間。
2、當使用者切換後,時鐘tab不可見時,記得onVisibilityChanged中停止發送訊息,不再重新整理時間。
android鬧鐘(三):實現時鐘功能