package com.example.time; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private TextView secText; private Button start; private int timeUsedInsec; /**********************************************************************************************/ private Handler uiHandle = new Handler(){ public void handleMessage(android.os.Message msg) { addTimeUsed(); //调取更新函数 updateClockUI(); //调取叠加函数 uiHandle.sendEmptyMessageDelayed(1, 1000); //1s,1000ms } }; /***********************************************************************************************/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); secText = (TextView) findViewById(R.id.sec); start = (Button) findViewById(R.id.start); start.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub uiHandle.removeMessages(1); startTime(); } }); } /***************************************************秒的输出**************************************************/ private void updateClockUI(){ secText.setText(getSec()); //更新秒 } /***************************************************秒的叠加*************************************************/ public void addTimeUsed(){ timeUsedInsec = timeUsedInsec + 1; //叠加1 } /***************************************************循环调取实现不断更新***********************************************/ private void startTime(){ uiHandle.sendEmptyMessageDelayed(1, 1000); // 调取uiHandle } /***************************************************定义什么才是一秒***********************************************/ public CharSequence getSec(){ int sec = timeUsedInsec % 60; // 求余数,叠加的数除以60,求余数 return sec < 10? "0" + sec :String.valueOf(sec); //如果秒小于10,秒前加“0”,如果秒不小于10,秒前面不加“0” } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
时间: 2024-10-15 03:49:31