我想在Android中创建一个从<1秒开始的慢秒表。除了一件事,一切都很好。我希望它慢意思是:
1.000/s //Start Time
1.001/s //After 10ms
1.002/s //After another 10ms
它不是真正的秒表,但它就像它。我需要为我正在创造的游戏增加每10毫秒的时间。请在模拟器或真实设备上测试代码以便更好地理解。
代码:
private void startTime() {
final long startTime = SystemClock.uptimeMillis();
timeHandler = new Handler(); //Handler
timeRunnable = new Runnable() { //Runnable
@Override
public void run() {
long timeInMilliseconds = SystemClock.uptimeMillis() - startTime + 1000; //Start time is 1.000/s
int secs = (int) (timeInMilliseconds / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (timeInMilliseconds % 1000);
if (timeInMilliseconds > 60000) {
score.setText(mins + ":" + String.format("%02d", secs) + "." + String.format("%03d", milliseconds) + "/s");
} else {
score.setText(String.format("%01d", secs) + "." + String.format("%03d", milliseconds) + "/s");
}
timeHandler.postDelayed(this, 0);
}
};
timeHandler.postDelayed(timeRunnable, 0);
}
请注意,得分只是一个显示时间的普通TextView。请帮我。感谢。
答案 0 :(得分:0)
经过多次试验和错误后,我找到了一个非常简单的解决方案,我将在此发布,以防将来有人面临像我一样的问题。
private void startTime() {
final long startTime = SystemClock.uptimeMillis();
timeHandler = new Handler();
timeRunnable = new Runnable() {
@Override
public void run() {
//Note the difference in the first two lines here.
long timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
//You can change this 20 according to what you want.
timeInMilliseconds = (timeInMilliseconds / 20) + 1000;
int secs = (int) (timeInMilliseconds / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (timeInMilliseconds % 1000);
if (timeInMilliseconds > 60000) {
score.setText(mins + ":" + String.format("%02d", secs) + "." + String.format("%03d", milliseconds) + "/s");
} else {
score.setText(String.format("%01d", secs) + "." + String.format("%03d", milliseconds) + "/s");
}
timeHandler.postDelayed(timeRunnable, 0);
}
};
timeHandler.postDelayed(timeRunnable, 0);
}
现在,秒表速度降低了。 我的时间每隔20毫秒增加1毫秒,而不是像之前在问题中提到的那样增加10毫秒,因为这更适合我。当然,您可以将此20更改为您想要的任何内容。