TimeView.java
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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); } }; }; }
小结:
1、在onFinishInflate中发送消息,实现时间的第一次显示。后来又在handler的handleMessage方法中发送消息,有点相当于调用死循环来刷新时间。
2、当用户切换后,时钟tab不可见时,记得onVisibilityChanged中停止发送消息,不再刷新时间。