Simple implementation and improvement of the Android countdown function

Source: Internet
Author: User
Tags stub time interval xmlns

Projects often encounter the ability to retrieve the password, and now find the password is generally used to receive authentication code, in order to prevent multiple transmission, the general need to set a send interval, such as 60 seconds. In order to let users feel more clearly this interval, so there is a countdown function. The following figure:

After clicking, the TextView or button that gets the verification code becomes not clickable, and its text will change every second, 59,58,57 ... After the last second, text changes to click to get the verification code, and it becomes clickable.

Read some predecessors wrote the countdown, are used handler and timertask to achieve, and then I found a simpler, Android comes with the class to write this function.

Next I'll use a simple example to implement this feature.

1, Activity_main. XML, for a button.

<relativelayout xmlns: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"
>

<button
Android:textsize= "25DP"
Android:id= "@+id/btn_get"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:text= "Click to get Verification code"/>

</RelativeLayout>

2, Mainactivity.java, both for the plays, but also extremely simple.

Package COM.EXAMPLE.RR;

Import android.app.Activity;
Import Android.graphics.Color;
Import Android.os.Bundle;
Import Android.os.CountDownTimer;
Import Android.util.Log;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
public class Mainactivity extends activity {

Private button mbutton;//defines a button
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
mbutton= (Button) Findviewbyid (r.id.btn_get);//←← get button ID
Set up listening ↓↓
Mbutton.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
Mbutton.setclickable (FALSE);
Mbutton.settextcolor (Color.parsecolor ("#FF0000 ″)");
MyTimer mytimer=new MyTimer (5000, 1000);//To define MyTimer objects
Mytimer.start ()//Start Countdown
}});

}
Private class MyTimer extends countdowntimer{

Millisinfuture for you set the total length of the countdown, such as 60 seconds to set to 60000
Countdowninterval for you to set the time interval, such as generally 1 seconds, as required to customize.
Public MyTimer (Long millisinfuture, long Countdowninterval) {
Super (Millisinfuture, countdowninterval);
TODO auto-generated Constructor stub

} @Override
public void Ontick (long millisuntilfinished) {
TODO auto-generated Method Stub
Mbutton.settext (millisuntilfinished/1000+ "seconds later regain");
}
Every time you set the interval to do the operation ↑↑
Operation at the end of the countdown ↓↓
@Override
public void OnFinish () {
TODO auto-generated Method Stub
Mbutton.setclickable (TRUE);
Mbutton.settextcolor (Color.parsecolor ("#000000"));
Mbutton.settext ("Click to obtain verification code");
}}}

At each key point I also made a note, below is the GIF I recorded for you.

Timer

You can see that there are 2 questions:

1, in 1 seconds, will pause for about two seconds, so that the user is not very good experience, but also thought it was a mobile phone card. Why is there such a problem?

2. When you click the button, the number 4 instead of the number 5 appears.

First we need to know the principle of this method, we first look at the Countdowntimer Source:

First of all, we look at this sentence: Mstoptimeinfuture = systemclock.elapsedrealtime () + mmillisinfuture;

Then look at the following sentence: final long millisleft = Mstoptimeinfuture–systemclock.elapsedrealtime ();

(Note: Systemclock.elapsedrealtime () returns the system runs to the present time, every moment is changing);

If a simple mathematical calculation, then the first mstoptimeinfuture is equal to millisleft, but otherwise, systemclock.elapsedrealtime () return time, in milliseconds, that is to say, Running from above to below, also consumes a little time, then Millisleft is less than 5000.

Back to our activity, what did we write in the Ontick of the inner class?

Mbutton.settext (millisuntilfinished/1000+ "seconds later"); then 4,900 is divided by 1000, and the return value is 4.

Solution:

When we instantiate MyTimer, we change 5000 to 6000.

As for the 1-second pause, let's take a look at the following if Else statement:

if (millisleft <= 0) {
OnFinish ();
else if (Millisleft < Mcountdowninterval) {
No tick, just delay until done
Sendmessagedelayed (Obtainmessage (MSG), millisleft);
} else {
Long Lasttickstart = Systemclock.elapsedrealtime ();
Ontick (Millisleft);

In the ELSE if statement, when millisleft<mcountdowninterval=1000, only pauses, without calling the Ontick method, that is, when we run the program, the Millisleft value is more than 4,900 ~3900~ 2900~1900~900,900, when you run here, it pauses, not the code we write in Ontick.

Solution:

Rewrite the Countdowntimer class.

And then

1. Add Ontick (millisleft) in else if;

2. Delete this if Else statement

OK, after I rewrite the class, I can still do the countdown function by changing the IF Else statement to the following:

if (millisleft <= 0) {
OnFinish ();
} else {
Ontick (Millisleft);
Sendmessagedelayed (Obtainmessage (MSG), 1000);
}

The effect GIF is as follows:

Is it difficult to write this kind of Daniel or do I have a problem with this method? Have to know the friends can contact me ~ Thank you!

PS: Write this article wasted a quick afternoon, because the network is not good, quickly finished, save the draft, and then there are accidents, resulting in no save, so,,, but still hope to get your suggestions and encouragement, thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.