zoukankan      html  css  js  c++  java
  • 假期学习记录9(Timer实现超简单的计时功能)

    在layout文件中添加一个文本框

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <TextView
            android:id="@+id/timerView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="60sp" />
    
    </LinearLayout>


    在对应的java文件中添加如下代码

    package com.example.lastgps;
    
    import android.os.Handler;
    import android.os.Message;
    import java.util.Timer;
    import android.os.SystemClock;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    import java.text.DecimalFormat;
    import java.util.TimerTask;
    
    public class time extends AppCompatActivity {
        private TextView timerView;
        private TextView runspeed;
        private long baseTimer;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_time);
            time.this.baseTimer = SystemClock.elapsedRealtime();
            timerView = (TextView) this.findViewById(R.id.timerView);
            final Handler startTimehandler = new Handler() {
                public void handleMessage(android.os.Message msg) {
                    if (null != timerView) {
                        timerView.setText((String) msg.obj);
                    }
                }
            };
            new Timer("开机计时器").scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    int time = (int) ((SystemClock.elapsedRealtime() - time.this.baseTimer) / 1000);
                    String hh = new DecimalFormat("00").format(time / 3600);
                    String mm = new DecimalFormat("00").format(time % 3600 / 60);
                    String ss = new DecimalFormat("00").format(time % 60);
                    String timeFormat = new String(hh + ":" + mm + ":" + ss);
                    Message msg = new Message();
                    msg.obj = timeFormat;
                    startTimehandler.sendMessage(msg);
                }
    
            }, 0, 1000L);
    
        }
    }


    运行结果如下

  • 相关阅读:
    KooTeam
    nopCommerce架构分析系列(一)nopCommerce简介
    NServiceBus最流行的开源企业服务总线 for .Net资源学习篇
    How to become a software architect?
    DotNetMQ: A Complete Message Queue System for .NET
    CSLA.Net专注电子商务 – Focus on eCommerce
    .net framework从1.0说到4.0
    ERP/SCM
    泛型接口的协变和逆变
    HTML5学习
  • 原文地址:https://www.cnblogs.com/837634902why/p/12293132.html
Copyright © 2011-2022 走看看