This article uses the Countdowntimer class in Android to achieve the countdown function, similar to the input phone number to obtain a verification code. The interface looks like this:
1. Click "Start Timer" button to start the countdown,
2. Countdown process:
3. After the time is over, the button changes to "re-verify" and then restarts the timer after clicking.
The functionality is simple and the Java code is as follows:
Public classMainactivityextendsActivity {Privatetimecount time; PrivateButton checking; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); time=NewTimecount (60000, 1000);//Create a Countdowntimer object (set time of 60 seconds)checking =(Button) Findviewbyid (R.id.button1); Checking.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {time.start ();//Start Timing } }); } /*** Countdown Inner class*/ classTimecountextendsCountdowntimer { PublicTimecount (LongMillisinfuture,Longcountdowninterval) { Super(Millisinfuture, Countdowninterval);//parameters: Total Duration, timing interval} @Override Public voidOnFinish () {//trigger When timing is completeChecking.settext ("Re-verify"); Checking.setclickable (true); } @Override Public voidOnTick (Longmillisuntilfinished) {//Timing Process DisplayChecking.setclickable (false); Checking.settext (millisuntilfinished/1000 + "seconds"); } }}
Layout code:
<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context= "Com.example.testandroid.MainActivity" > <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/phone_number" /> <EditTextAndroid:hint= "@string/input_number"Android:layout_weight= "1"Android:layout_width= "0DP"Android:layout_height= "Wrap_content" /> <ButtonAndroid:id= "@+id/button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/begin" /></LinearLayout>
Mainly from: http://www.cnblogs.com/-cyb/archive/2011/12/18/Android_CountDownTimer.html, I slightly finishing.
Android Countdowntimer Class Implementation Countdown