The project needs to implement a timing function, although the use of chronometer can be very convenient to achieve the timing function, but need a countdown control.
Baidu has a number of methods, the countdown is not, so with chronometer encapsulated a countdown class, the spirit of open source, to share to everyone!
Nonsense don't say that go into the subject
First, the XML layout is as follows:
<com.example.anticlockwisedemo.anticlockwise
android:id= "@+id/id_timer"
android:layout_width= "Wrap_ Content "
android:layout_height=" wrap_content "
android:textsize=" 66sp "/>
Inherit chronometer encapsulated classes:
Package Com.example.anticlockwisedemo;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Android.annotation.SuppressLint;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import Android.widget.Chronometer; /*** * * @author Small _ lazy 2015/02/07 * */@SuppressLint ({"Viewconstructor", "SimpleDateFormat"}) public Class A Ticlockwise extends Chronometer {public anticlockwise (context, AttributeSet attrs) {Super (context, attrs)
;
TODO automatically generated constructor stub Mtimeformat = new SimpleDateFormat ("Mm:ss");
This.setonchronometerticklistener (listener);
Private long mtime;
Private long mnexttime;
Private Ontimecompletelistener Mlistener;
Private SimpleDateFormat Mtimeformat;
Public Anticlockwise {Super (context);
/** * Restart timing/public void restart (long _time_s) {if (_time_s = = 1) {mnexttime = Mtime;
else {mtime = Mnexttime = _time_s;
} this.start (); }
public void Restart () {Restart (-1);
/** * Continue to Timer/public void Onresume () {This.start ();
/** * Pause Timer/public void OnPause () {this.stop (); /** * Set Time format * * @param pattern * Timing Format/public void Settimeformat (String) {Mtimeformat =
New SimpleDateFormat (pattern);
public void Setontimecompletelistener (Ontimecompletelistener l) {mlistener = l; } Onchronometerticklistener Listener = new Onchronometerticklistener () {@Override public void Onchronometertick
(chronometer chronometer)
{if (mnexttime <= 0) {if (Mnexttime = = 0) {Anticlockwise.this.stop ();
if (null!= mlistener) mlistener.ontimecomplete ();
} mnexttime = 0;
Updatetimetext ();
Return
} mnexttime--;
Updatetimetext ();
}
};
/** * Initialization time * @param _time_s/public void Inittime (long _time_s) {mtime = Mnexttime = _time_s;
Updatetimetext (); private void Updatetimetext ()
{This.settext (Mtimeformat.format) (New Date (Mnexttime * 1000));
} interface Ontimecompletelistener {void Ontimecomplete (); }
}
Effect Chart:
The procedure is very simple, I do not do too much explanation.
Detailed you can see the demo, has been encapsulated, can be used directly, download address: Http://xiazai.jb51.net/201611/yuanma/androidChronometer (jb51.net). rar
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.