android鬧鐘(三):實現時鐘功能

來源:互聯網
上載者:User

標籤:

 

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鬧鐘(三):實現時鐘功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.