packagecom.example.administrator.myapplication;importandroid.os.SystemClock;importandroid.support.v7.app.AppCompatActivity;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.Chronometer;importandroid.widget.Toast;public class MainActivity extends AppCompatActivity implementsView.OnClickListener,Chronometer.OnChronometerTickListener{privateChronometer chronometer;privateButton btn_start,btn_stop,btn_base;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}private voidinitView() {
chronometer=(Chronometer) findViewById(R.id.chronometer);
btn_start=(Button) findViewById(R.id.btnStart);
btn_stop=(Button) findViewById(R.id.btnStop);
btn_base=(Button) findViewById(R.id.btnReset);
chronometer.setOnChronometerTickListener(this);
btn_start.setOnClickListener(this);
btn_stop.setOnClickListener(this);
btn_base.setOnClickListener(this);
}
@Overridepublic voidonClick(View v) {switch(v.getId()){caseR.id.btnStart:
chronometer.start();//开始计时
break;caseR.id.btnStop:
chronometer.stop();//停止计时
break;caseR.id.btnReset:
chronometer.setBase(SystemClock.elapsedRealtime());//复位
break;
}
}
@Overridepublic voidonChronometerTick(Chronometer chronometer) {
String time=chronometer.getText().toString();if(time.equals("00:00")){
Toast.makeText(MainActivity.this,"开始计时",Toast.LENGTH_SHORT).show();
}
}
}