如何存储暂停的计时器时间并以另一种方式显示它

How to store paused chronometer time and display it another view

我已将我的计时器设置为在需要时启动,在需要时暂停并在满足条件时重置。很棒,但还不够完美。我希望能够在满足条件时存储计时器显示的时间,例如“01.12”,然后在 TextView 中显示该时间。

目标是显示完成游戏所花的时间,并将其显示在我的 LinearLayout 中(游戏结束时弹出,然后重置游戏)。

我试过将时间存储为 long 和 double,但我不太幸运,因为我不知道如何真正做到这一点。以下是满足我想要满足的条件时我的屏幕显示的内容。

for (int[] winningPosition : winningPositions) {

                if (gameState[winningPosition[0]] == gameState[winningPosition[1]] &&
                        gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
                        gameState[winningPosition[0]] != 2) {

                    if(running) {
                        chronometer.stop();
                        pauseOffSet = SystemClock.elapsedRealtime() - chronometer.getBase();
                        running = false;
                    }
                    // Someone has won!

                    String winner = "Red";

                    //prints a 0 or 1 depending on who has won
                    if (gameState[winningPosition[0]] == 0) {

                        chronometer.stop();

                        winner = "Yellow";

                    }

                    TextView winnerMessage = findViewById(R.id.winnerMessage);

                    winnerMessage.setText(winner + " has won!");

                    LinearLayout layout = findViewById(R.id.playAgainLayout);
                    Animation slideUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up);

                    if(layout.getVisibility()==View.INVISIBLE){

                        layout.startAnimation(slideUp);
                        layout.setVisibility(View.VISIBLE);
                    }
                }
            }

预期的结果是像这样将暂停时间放入 TextView

TextView pausedTime = findViewById (R.id.pausedTimeTV);

pausedTime.chronoTime() (?)

感谢所有帮助。

您可以使用 SimpleDateFormat 以您要查找的格式安排时间。

if(isRunning){
    chronometer.stop();

    long stoppedTime = SystemClock.elapsedRealtime() - chronometer.getBase();

    // Create the desired format
    SimpleDateFormat formatter = new SimpleDateFormat("mm:ss", Locale.getDefault());

    myTextView.setText(formatter.format(stoppedTime)); // Set the formatted time in the textview
}

https://developer.android.com/reference/java/text/SimpleDateFormat

提供了有关格式化的更多信息