Android 开发第六弹:简易时钟(计时器)

接上篇Android 开发第五弹:简易时钟(闹钟) ,这次是一个时钟类应用,目前依旧是主要的功能,长得还是很挫。当然了,核心功能是有的……

这里写图片描述

时钟

先把简单的时钟给列出来吧,这里都写的很简单,即便要用世界各个城市的话,也只是相应的加上或减去几个小时。

新建TimeView类,并扩展自LinearLayout,然后布局文件和上一篇中那么写就好了。

<myapplication.nomasp.com.clock.TimeView
    android : id = "@+id/tabTime"
    android : layout_width = "match_parent"
    android : layout_height = "match_parent"
    android : orientation = "vertical">

    <TextView
        android : id = "@+id/tvTime"
        android : textAppearance = "?android:attr/textAppearanceLarge"
        android : layout_width = "match_parent"
        android : layout_height = "match_parent"
        android : gravity = "center" / >
</myapplication.nomasp.com.clock.TimeView>
    // 实例化TextView控件
    private TextView tvTime;

    public TimeView(Context context) {
        super(context);
    }

    public TimeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TimeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate(){
        super.onFinishInflate();

        tvTime = (TextView)findViewById(R.id.tvTime);
        tvTime.setText("H");

        timeHandler.sendEmptyMessage(0);
    }

    private Handler timeHandler = new Handler() {

        public void handleMessage(Message msg){
            // 刷新时间
            refreshTime();

            if(getVisibility() == View.VISIBLE){
                timeHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };

    // 刷新时间
    private void refreshTime(){
        Calendar c = Calendar.getInstance();

        // 试着显示的时间格式 
        tvTime.setText(String.format("%d:%d:%d",
                c.get(Calendar.HOUR_OF_DAY),
                c.get(Calendar.MINUTE),
                c.get(Calendar.SECOND)));
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);

        if(visibility == View.VISIBLE){
            timeHandler.sendEmptyMessage(0);
        }else{
            timeHandler.removeMessages(0);
        }
    }

就这些了,下面正式开始计时器的部分。

TimerView

TimerView类同样是扩展自LinearLayout,并且布局的写法也是如出一辙:

<myapplication.nomasp.com.clock.TimerView
    android : id = "@+id/tabTimer"
    android : layout_width = "match_parent"
    android : layout_height = "match_parent"
    android : orientation = "vertical">

    <LinearLayout
        android : orientation = "horizontal"
        android : layout_width = "match_parent"
        android : layout_height = "wrap_content">

    &l
  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值