本节书摘来自异步社区《Android UI基础教程》一书中的第2章,第2.7节完成TIMETRACKER,作者 【美】Jason Ostrander,更多章节内容可以访问云栖社区“异步社区”公众号查看
2.7 完成TIMETRACKERAndroid UI基础教程基本上关于第一个TimeTracker应用程序所需的所有内容我们都讲过了。现在只需要一些处理按键的逻辑。
1.回到TimeTrackerActivity的onCreate方法,并加上以下代码:
`Button startButton = (Button) findViewById(R.id.start`_`stop);` `startButton.setOnClickListener(this);` `Button stopButton = (Button) findViewById(R.id.reset);` `stopButton.setOnClickListener(this);`这会让TimeTrackerActivity类能够监听按钮事件。你将会在下一章中了解关于事件处理的知识。但仅就现在来说,只需要更新TimeTrackerActivity来实现OnClickListener接口。
2.重写onClick方法。每当一个按钮被按下都会调用这个方法。
`@Override` ` public void onClick(View v) {` ` TextView ssButton = (TextView) findViewById` ` → (R.id.start`_`stop);`3.检查哪个按钮被按下了。如果用户按下了Start/Stop按钮,检查定时器的状态。如果它被停止了,你需要重新启动并将按钮文字改为“Stop”;反之,则需要停止计时器并把按钮文字改为“Start”。
` if (v.getId() == R.id.start`_`stop) {` ` if (isTimerStopped()) {` ` startTimer();` ` ssButton.setText(R.string.stop);` ` } else {` ` stopTimer();` ` ssButton.setText(R.string.start);` ` }`4.如果用户按下了Reset按钮,重置定时器和TextView变量counter,并把Start/Stop按钮的文字设为“Start”:
` } else if (v.getId() == R.id.reset) {` ` resetTimer();` ` TextView counter = (TextView) findViewById` ` → (R.id.counter);` ` counter.setText(DateUtils.formatElapsedTime(0));` ` ssButton.setText(R.string.start);` ` }` ` }`现在你可以运行应用了!它运行起来应该像图2.14一样。
你应该可以启动以及暂停计时器并在列表中记录之前的数值。在下一章节中,你将会更进一步—扩展应用使其可用于不同的屏幕尺寸、添加一些通知,以及使得应用在后台运行。
相关资源:g-timetracker:全球时间跟踪器-源码