如何在 5 秒内将 TextView 中的 0
计数到 number
?
number
变量始终具有不同的值,这就是为什么我需要它始终在 5 秒内从 0
计数到 number
。
如果我执行 while
且 number
= 1982654324441,则需要很长时间才能计算出来。
这就是我现在的做法:
new Thread(new Runnable() {
public void run() {
while (counter < number) {
try {
Thread.sleep(0,01);
} catch (InterruptedException e) {
e.printStackTrace();
}
textView.post(new Runnable() {
public void run() {
textView.setText("" + counter);
}
});
counter++;
}
}
}).start();
最佳答案
试试这个方法:它应该适用于所有大于 0 的数字,您还可以调整更新间隔。
final int TIME_TO_COUNT = 5000; //ms
//Update interval in ms. Consider that the screen cannot be updated as often as you want.
//17ms (about 60FPS) sound reasonable
final int UPDATE_INTERVAL = 17;
final int number = 5001; //Can be any number between 0 and Integer.MAX_VALUE;
new Thread(new Runnable() {
public void run() {
double counter = 0.0;
while (counter < number) {
try {
Thread.sleep(UPDATE_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
textView.post(new Runnable() {
public void run() {
textView.setText(String.valueOf(Math.ceil(counter)));
}
});
counter += (number / (double) TIME_TO_COUNT) * UPDATE_INTERVAL;
}
}
}).start();
关于java - 统计特定时间段内的数字,Java,Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434969/