【问题标题】:How to create a slow stopwatch in android?如何在android中创建一个慢秒表?
【发布时间】:2015-12-19 21:34:22
【问题描述】:

我想在 android 中创建一个从 1 秒开始的 slow 秒表。除了一件事,一切都很好。我希望它是 slow 意思是:

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);
}

注意 score 只是一个普通的 TextView 来显示时间。请帮我。谢谢。

【问题讨论】:

    标签: android time runnable stopwatch android-handler


    【解决方案1】:

    经过多次尝试和错误,我找到了一个非常简单的解决方案,我会在这里发布,以防将来有人遇到像我一样的问题。

    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 改成你想要的任何东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      相关资源
      最近更新 更多