1.activity_main.xml:
1 <Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"2 Xmlns:tools= "Http://schemas.android.com/tools"3 Android:layout_width= "Match_parent"4 Android:layout_height= "Match_parent" >5 <Button6 Android:id= "@+id/btn_time"7 Android:layout_width= "Wrap_content"8 Android:layout_height= "Wrap_content"9 Android:text= "Get Verification Code" />Ten </Relativelayout>
2.mainactivity.java:
1 Public classMainactivityextendsActivity {2 PrivateButton Mtimebutton;3 Privatetimecount time;4 @Override5 protected voidonCreate (Bundle savedinstancestate) {6 Super. OnCreate (savedinstancestate);7 requestwindowfeature (window.feature_no_title);8 Setcontentview (r.layout.activity_main);9Mtimebutton =(Button) Findviewbyid (r.id.btn_time);TenTime =NewTimecount (60000, 1000); OneMtimebutton.setonclicklistener (NewOnclicklistener () { A @Override - Public voidOnClick (View v) { - Time.start (); the } - }); - } - /** + * Inherit Countdown class - * @author + */ A classTimecountextendsCountdowntimer { at /** - * Construction Method - * @parammillisinfuture - * Total countdown long milliseconds - * @paramCountdowninterval - * Countdown Interval in */ - PublicTimecount (LongMillisinfuture,Longcountdowninterval) { to Super(Millisinfuture, countdowninterval); + } - @Override the Public voidOnTick (Longmillisuntilfinished) { *Mtimebutton.setenabled (false); $Mtimebutton.settext (millisuntilfinished/1000 + "SEC");//millisuntilfinished indicates the current completed timePanax Notoginseng } - @Override the Public voidOnFinish () {//End of timing +Mtimebutton.setenabled (true); AMtimebutton.settext ("Get Back"); the } + } -}
The Timecount class is used here, and when initialized, two parameters are passed in, Millisinfuture and countdowninterval,millisinfuture represent start()
the number of milliseconds from the beginning of the call to the completion of the countdown and onFinish()
the method being called. That is, a cycle; Countdowninterval represents the time interval for receiving ontick (long) callbacks. This example uses a 60-second period and a 1-second interval. Timecount inherits from the Countdowntimer class, covering the Ontick method inside, this method is executed during the counting process, borrowing the setenabled method, turning the button into a non-clickable state, and updating the time displayed on the button. The OnFinish method, which is triggered at the end of the timer, sets the button to a clickable state and changes the text on the button to "regain".
Android Learning Small Example--Verification Code Countdown button