I\'d like a simple mm:ss
timer to be displayed on my actionbar, be able to pick the number of minutes to start counting down from and then call a method once it\'s
I've managed to do that by adding a TextView
to the Action Bar as an Action View in the menu, then updating it at regular intervals using a CountDownTimer
.
(Tested on an Android 3.0 emulator, an Android 4.3 emulator and a real device running Android 4.3).
Here's the XML for the menu item. Note that actionViewClass="android.widget.TextVew"
(showAsAction and actionViewClass don't have the android namespace because I'm using the support action bar).
In onCreateOptionsMenu
, I find the MenuItem
and call getActionView
to assign it to private TextView
, timerText
. I also apply some padding here, so that it's not right at the edge of the screen.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.break_timer, menu);
MenuItem timerItem = menu.findItem(R.id.break_timer);
timerText = (TextView) MenuItemCompat.getActionView(timerItem);
timerText.setPadding(10, 0, 10, 0); //Or something like that...
startTimer(30000, 1000); //One tick every second for 30 seconds
return true;
}
I have a method called startTimer
to start a CountDownTimer
and update timerText
in its onTick
. I call startTimer
from onCreateOptionsMenu
to ensure that timerText
is not accessed before it has been initialised. (Previously, I called startTimer
from onCreate
, but got a NullPointerException
).
private void startTimer(long duration, long interval) {
CountDownTimer timer = new CountDownTimer(duration, interval) {
@Override
public void onFinish() {
//TODO Whatever's meant to happen when it finishes
}
@Override
public void onTick(long millisecondsLeft) {
int secondsLeft = (int) Math.round((millisecondsLeft / (double) 1000));
timerText.setText(secondsToString(secondsLeft));
}
};
timer.start();
}
I'm sure that anyone reading this will know a better way to convert an integer number of seconds to a timecode such as "00:00:00", but just in case I'll share the secondsToString
method I used in onTick
, above.
private String secondsToString(int improperSeconds) {
//Seconds must be fewer than are in a day
Time secConverter = new Time();
secConverter.hour = 0;
secConverter.minute = 0;
secConverter.second = 0;
secConverter.second = improperSeconds;
secConverter.normalize(true);
String hours = String.valueOf(secConverter.hour);
String minutes = String.valueOf(secConverter.minute);
String seconds = String.valueOf(secConverter.second);
if (seconds.length() < 2) {
seconds = "0" + seconds;
}
if (minutes.length() < 2) {
minutes = "0" + minutes;
}
if (hours.length() < 2) {
hours = "0" + hours;
}
String timeString = hours + ":" + minutes + ":" + seconds;
return timeString;
}