I have set my chronometer to start when needed, pause when required and reset when a condition is met. Great, but not quite perfect. I want to be able to store the time the chronometer shows, say "01.12", when a condition is met and then display that time in a TextView.
The goal is to show how long it took to finish the game played, and display this in my LinearLayout (that pops up when the game is finished, before resetting the game).
I've tried storing the time as a long and a double, but I'm not getting much luck as I don't know how to really do that. Below is what my screen shows when the condition I want to meet, is met.
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);
}
}
}
The expected result is to place the paused time into a TextView like so
TextView pausedTime = findViewById (R.id.pausedTimeTV);
pausedTime.chronoTime() (?)
Thanks for any and all help.
You can use a SimpleDateFormat
to arrange the time in the format you're looking for.
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
}
There's more information about formatting at https://developer.android.com/reference/java/text/SimpleDateFormat