【问题标题】:android string.format not formatting correctly with a timerandroid string.format 没有使用计时器正确格式化
【发布时间】:2014-12-01 08:24:31
【问题描述】:

我有一个显示计时器的文本视图,并且我使用 string.format,因此秒数将始终使用 2 位数字:0:00

但是当我达到 10 分钟(分钟也上升到两位数)时,秒只使用一位而不是两位。

timerRunnable:

Runnable timerRunnable = new Runnable() {

    @Override
    public void run() {


        millis = System.currentTimeMillis() - startTime;

        aSeconds = (int) (millis / 1000) + paSeconds;


        seconds = (int) (millis / 1000) + pSeconds;
        minutes = seconds / 60 + pMinutes;
        seconds = seconds % 60;



        timerTextView.setText(String.format("%d:%02d", minutes, seconds));

        if(aSeconds == delay){

            Toast.makeText(getApplicationContext(), "Drink",
                    Toast.LENGTH_LONG).show();

            delay += delay;
            count += 1;

            Log.d("MainActivity", "" + count);

        }

        timerHandler.postDelayed(this, 1000);


    }
};

问题是我将 String.format 设置为基本上只包含 3 个数字的组合,但我找不到解决问题的聪明方法

【问题讨论】:

  • 可能我不明白,但你为什么不把 timerTextView.setText(minutes+":"+seconds) 放在一起? (如果您需要添加前导零)
  • 这使得当秒不是两位数时,第二位将自动替换为 0。有没有更好的方法来做到这一点?

标签: java android string.format


【解决方案1】:

你试过 if..else 吗?

if (minute >=10 && minute<=59)
   timerTextView.setText(String.format("02%d:%02d", minutes, seconds));

else       
   timerTextView.setText(String.format("2%d:%02d", minutes, seconds));

还有什么是 pSeconds?

【讨论】:

  • 好的,我刚刚尝试使用 if 方法设置它,将在 10 分钟内报告:) pSeconds 是我手动暂停的方式。当用户按下暂停时,pSeconds 将被分配秒值,当恢复时,秒数将等于以前的值。
【解决方案2】:

解决方案只是让我的文本视图在计时器达到 10 分钟时变小,它只是没有显示在屏幕上..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多