码:
Run Code Online (Sandbox Code Playgroud)public class SMH extends Activity { public void onCreate(Bundle b) { super.onCreate(b); setContentView(R.layout.main); TextView tv = (TextView) findViewById(R.id.tv); new CountDownTimer(10000, 2000) { public void onTick(long m) { long sec = m/1000+1; tv.append(sec+" seconds remain\n"); } public void onFinish() { tv.append("Done!"); } }.start(); }
输出:
10秒保持
8秒保持
6秒保持
4秒保持
完成!
问题:
如何让它显示" 2秒仍然 "?经过的时间确实是10秒,但最后一次onTick()从未发生过.如果我将第二个参数从2000更改为1000,那么这是输出:
10秒保持
9秒保持
8秒保持
7秒保持
6秒保持
5秒保持
4秒保持
3秒保持
2秒保持
完成!
所以你看,它似乎正在跳过最后一次onTick()调用.顺便说一句,XML文件基本上是默认的main.xml,TextView分配了id tv,文本设置为"".
为什么使用CountDownTimer两次显示"1"?我只是想让它顺利倒计时,而不是看起来它在最后一秒被挂断了.有人对如何解决这个问题有任何想法?
以下是Android Developers页面中的代码:
new CountdownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Run Code Online (Sandbox Code Playgroud)
我创建了一个新项目并复制并粘贴了这段代码,以确保我不会在程序中意外搞乱.我一直在使用Tab 10.1进行测试.当我运行它时它会这样做:"5","4","3","2","1","1","完成!".