码迷,mamicode.com
首页 > 移动开发 > 详细

android闹钟(三):实现时钟功能

时间:2015-07-22 18:11:29      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

 

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闹钟(三):实现时钟功能

标签:

原文地址:http://www.cnblogs.com/2015android/p/4667967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!