如何存储暂停的计时码表时间并在其他视图中显示

时间:2019-07-03 22:27:02

标签: java android chronometer

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

目标是显示完成游戏所花费的时间,并将其显示在我的LinearLayout中(该游戏完成后会在重置游戏之前弹出)。

我尝试将时间存储为一倍和一倍,但是我运气不佳,因为我不知道该怎么做。以下是我要满足的条件得到满足时我的屏幕上显示的内容。

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()(?)

感谢所有帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用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