在 Android 中允许按钮在一定时间内给予积分
我只看到有关如何在一定时间后执行某些操作的文章,但我想知道如何在 Android 中执行特定时间的某些操作。
public void buttonClick(View v) {
currentUser.changeScore(10);
TextView tv = (TextView) findViewById(R.id.score);
tv.setText("Score: " + currentUser.getScore());
}
我希望用户能够在事件发生后 10 秒内按下按钮并获得积分。在那 10 秒之后,如果按下按钮,我希望用户失去 10 分。
I am only seeing articles on how to do something after a certain amount of time, but I want to know how to do something FOR a certain amount of time in Android.
public void buttonClick(View v) {
currentUser.changeScore(10);
TextView tv = (TextView) findViewById(R.id.score);
tv.setText("Score: " + currentUser.getScore());
}
I want to the user to be able to press the button and gain points for 10 seconds after an Event has occured. After those 10 seconds, I want the user to lose 10 points if the button is pressed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这很简单。每次事件发生时,设置一个变量,如下所示:
您并不是真的希望在该时间间隔内定期更改任何内容 - 事件只是设置一个新的时间点,如下所示何时“可以”单击按钮的边界。不需要计时器或类似的东西。
(为了可测试性,您可能需要依赖注入的
Clock
类型或类似的类型来提供“当前时间”功能,但基本原理是相同的。)It's simple. Every time your event happens, set a variable, like this:
It's not like you're really wanting anything to change on a regular basis during that interval - the event is just setting a new point in time as the boundary of when it's "good" to click the button. No need for a timer or anything like that.
(For testability you may want to have a dependency-injected
Clock
type or something similar to provide the "current time" functionality, but the basic principle is the same.)您可以使用计时器:
然后按钮单击处理程序将是:
You may use Timer:
Then button click handler will be: