Skip to content

Instantly share code, notes, and snippets.

@alxmjo
Last active May 17, 2016 04:54
Show Gist options
  • Save alxmjo/8cd2960148d17d20307d to your computer and use it in GitHub Desktop.
Save alxmjo/8cd2960148d17d20307d to your computer and use it in GitHub Desktop.
// Tag used for logging
private static final String TAG = "MyActivity";
// Declare a countdown timer
private CountDownTimer countDownTimer;
// Declare and initialize length for timer to run and set total equal to it
private long length = 30000;
private long total = length;
// Declare TextView and ProgressBar to update view
private TextView timeRemaining;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Initialize timeRemaining and progressBar views
timeRemaining = (TextView) findViewById(R.id.time_remaining_text_view);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
// Set progress bar max value equal to length
progressBar.setMax((int) length);
}
// Define onClick method for Start button
public void startTimer(View v) {
// Instantiate new CountDownTimer and assign to countDownTimer variable
countDownTimer = new CountDownTimer(total, 1) {
@Override // Implement required methods (onTick and onFinish)
public void onTick(long millisUntilFinished) {
// Update total with remaining time left
total = millisUntilFinished;
// Update TextView and ProgressBar
timeRemaining.setText("seconds remaining: " + millisUntilFinished / 1000);
progressBar.setProgress((int) (progressBar.getMax() - millisUntilFinished));
}
@Override
public void onFinish() {
// Update TextView
timeRemaining.setText("done!");
// Reset total to length so Start begins at beginning
total = length;
}
};
// Start countDownTimer
countDownTimer.start();
}
public void stopTimer(View v) {
countDownTimer.cancel();
Log.v(TAG, "stopped");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment