您现在的位置是:首页 > 文章详情

《Android UI基础教程》——2.7节完成TIMETRACKER

日期:2017-05-01点击:402

本节书摘来自异步社区《Android UI基础教程》一书中的第2章,第2.7节完成TIMETRACKER,作者 【美】Jason Ostrander,更多章节内容可以访问云栖社区“异步社区”公众号查看

2.7 完成TIMETRACKER
Android 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一样。


e950699435da94e0cb083047b1bdd5e53d7cc7cc

你应该可以启动以及暂停计时器并在列表中记录之前的数值。在下一章节中,你将会更进一步—扩展应用使其可用于不同的屏幕尺寸、添加一些通知,以及使得应用在后台运行。

原文链接:https://yq.aliyun.com/articles/102888
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章