public class MainActivity extends AppCompatActivity {
@Bind(R.id.timerText)
TextView timerText;
@Bind(R.id.pauseButton)
ImageButton pauseButton;
@Bind(R.id.restartButton)
ImageButton restartButton;
@Bind(R.id.startButton)
ImageButton startButton;
private CountDownTimer mCounter;
long millisecondsLeft;
boolean isFirstLaunch = true;
boolean isPaused = false;
boolean isRunning = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFirstLaunch) {
pauseButton.setVisibility(View.VISIBLE);
restartButton.setVisibility(View.VISIBLE);
startButton.setVisibility(View.GONE);
isFirstLaunch = false;
setTheTimer(60 * 25 * 1000);
} else {
isRunning = true;
isPaused = false;
changeVisibility();
setTheTimer(millisecondsLeft);
}
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCounter.cancel();
mCounter = null;
isRunning = false;
isPaused = true;
changeVisibility();
}
});
restartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restart();
}
});
}
public void changeVisibility () {
if (isPaused) {
startButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.GONE);
}
if (isRunning) {
pauseButton.setVisibility(View.VISIBLE);
startButton.setVisibility(View.GONE);
}
}
public void restart () {
if (mCounter != null) {
mCounter.cancel();
mCounter = null;
isRunning = true;
isPaused = false;
changeVisibility();
setTheTimer(60 * 25 * 1000);
} else {
isRunning = true;
isPaused = false;
changeVisibility();
setTheTimer(60 * 25 * 1000);
}
}
private void setTheTimer(long value) {
if (mCounter == null) {
mCounter = new CountDownTimer(value, 1000) {
@Override
public void onTick(long millisUntilFinished) {
long minutes = (millisUntilFinished / 1000) / 60;
int seconds = (int) ((millisUntilFinished / 1000) % 60);
millisecondsLeft = millisUntilFinished;
timerText.setText(minutes + ":" + seconds);
}
@Override
public void onFinish() {
timerText.setText("Done!");
}
};
mCounter.start();
}
}
}
The problem I'm having is in the bottom of the code I have provided. Its some code that I found in a forum and it has a problem which I cannot solve. My timer always starts at 25:0
and then proceeds to 24:59
. This also occurs later on in the display e.g.: 23:0
. I am trying to make the seconds always display two digits instead of just a single 0.