How To Change Format Of Chronometer?
Solution 1:
Here is an easy and smart solution for time format 00:00:00 in chronometer in android
ChronometertimeElapsed= (Chronometer) findViewById(R.id.chronomete);
timeElapsed.setOnChronometerTickListener(newOnChronometerTickListener(){
@OverridepublicvoidonChronometerTick(Chronometer cArg) {
longtime= SystemClock.elapsedRealtime() - cArg.getBase();
inth= (int)(time /3600000);
intm= (int)(time - h*3600000)/60000;
int s= (int)(time - h*3600000- m*60000)/1000 ;
Stringhh= h < 10 ? "0"+h: h+"";
Stringmm= m < 10 ? "0"+m: m+"";
Stringss= s < 10 ? "0"+s: s+"";
cArg.setText(hh+":"+mm+":"+ss);
}
});
timeElapsed.setBase(SystemClock.elapsedRealtime());
timeElapsed.start();
Solution 2:
I was dealing with the same issue. The easiest way to achieve this goal would be overriding updateText method of the Chronometer, but unfortunately it is a private method so I have done this in this way :
mChronometer.setText("00:00:00");
mChronometer.setOnChronometerTickListener(newChronometer.OnChronometerTickListener() {
@OverridepublicvoidonChronometerTick(Chronometer chronometer) {
CharSequencetext= chronometer.getText();
if (text.length() == 5) {
chronometer.setText("00:"+text);
} elseif (text.length() == 7) {
chronometer.setText("0"+text);
}
}
});
I know that it would be better to write custom widget but for small project it can be suitable.
Setting format on chronometer allows formatting text surrounding actual time and time is formatted using DateUtils.formatElapsedTime .
Hope that helps.
Solution 3:
In Kotlin, found a better solution with no memory allocation for the String every second
cm_timer.format = "00:%s"
cm_timer.setOnChronometerTickListener({ cArg ->
val elapsedMillis = SystemClock.elapsedRealtime() - cArg.base
if (elapsedMillis > 3600000L) {
cArg.format = "0%s"
}
else {
cArg.format = "00:%s"
}
})
where cm_timer
is Chronometer
Solution 4:
Chronometers setFormat method is used to add formated text like:
"Time %s from start"
resulting
"Time 00:00 from start"
In Chronometer you can not select between formats HH:MM:SS or MM:SS.
Solution 5:
// You can use this code. Setting the format and removing it//Removing the format (write this in oncreate)if (mChronometerformat) {
mSessionTimeChro.setOnChronometerTickListener(newOnChronometerTickListener() {
@OverridepublicvoidonChronometerTick(Chronometer chronometer) {
if (chronometer.getText().toString()
.equals("00:59:59"))
chronometer.setFormat(null);
}
});
}
// Setting the format
mSessionTimeChro.setBase(SystemClock.elapsedRealtime());
if (diffHours == 0) {
mSessionTimeChro.setFormat("00:%s");
mChronometerformat = true;
}
mSessionTimeChro.start();
Post a Comment for "How To Change Format Of Chronometer?"