Android Custom View get registration Verification Code Countdown button _android

Source: Internet
Author: User
Tags gettext

In the Android development, we will inevitably do the registration function, and now most of the registration is registered with the mobile phone, then the registration will be required to obtain the verification code to verify the way, we next to combat the custom get the Verification code Countdown button:

1. See the effect chart first

2. The variables we involve

Countdown time is long, you can set the

/**
 * Countdown length, the default countdown period of 60 seconds;
* Private long length = * 1000;

The text displayed by the button before clicking the button

/** * The text displayed by the button before clicking the button, the
 default is to get the verification code
/Private String Beforetext = "Get the authentication Code";

After the start of the countdown after the number of seconds to display the word

/** * After the
 start of the countdown after the number of seconds to display the word, the default is seconds
 * *
private String Aftertext = "seconds";

3. Using What countdown timer

In Java, the execution of a timer task requires two basic classes:
Java.util.Timer;
Java.util.TimerTask;

To run a timed task, the most basic steps are as follows:
1, establish a task to be performed timertask.
2, create a timer instance, through the timer provided by the schedule () method, the TimerTask added to the timer timer, while setting the rules to execute.

When the program executes the timer initialization code, the timer task is set to execute.
The schedule () method in a timer has several overloaded formats to accommodate different situations. The format of the method is as follows:
void Schedule (TimerTask task, Date time)
Schedules the specified task at the specified time.
void Schedule (timertask task, Date Firsttime, long period)
Schedules the specified task to begin repeating fixed-delay execution at a specified time.
void Schedule (TimerTask task, long delay)
Schedules the specified tasks to be performed after the specified delay.
void Schedule (TimerTask task, long delay, long period)
Schedules the specified task to begin repeating fixed-delay execution from the specified delay.
A timer is thread-safe, and this class can be extended to a large number of concurrent tasks (there are thousands of without problems). All of its construction methods start the timer thread. You can call Cancel () to terminate this timer and discard all currently scheduled tasks. Purge () removes all canceled tasks from this timer's task queue. This class does not provide a real-time guarantee: it uses the object.wait (long) method to schedule the task.
TimerTask is an abstract class that is scheduled by a Timer for a task that is executed or repeated at one time. It has an abstract method run ()-the action to be performed by the timer task. Therefore, each specific task class must inherit the TimerTask class and override the run () method. In addition, it has two non-abstract methods:
Boolean cancel ()
Cancels this timer task.
Long Scheduledexecutiontime ()
Returns the scheduled execution time for the most recent actual execution of this task.

4. Code

Import Android.content.Context;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.text.TextUtils;
Import Android.util.AttributeSet;
Import Android.view.View;

Import Android.widget.Button;
Import Java.util.Timer;

Import Java.util.TimerTask;
 /** * Custom Countdown button * <p/> * * @author Dylan * [Buddha bless never Bug] * Created by Dylan on 2016/10/5 0005. * * public class Countdownbutton extends Button implements View.onclicklistener {/** * countdown length, default countdown time of 60 seconds; * * Priv
  ate long length = 60 * 1000;
  /** * Start to perform the timer class, you can implement the interval task per second * * Private timer timer;
  /** * The task to be performed after the time of every second * * Private timertask timertask;
  /** * The text displayed by the button before the button is clicked, the default is to obtain the verification code/private String Beforetext = "Obtain the authentication code";
  /** * After the start of the countdown after the number of seconds to display the word, the default is seconds * * Private String Aftertext = "seconds";


  /** * button click event * * Private Onclicklistener Onclicklistener;
    Public Countdownbutton {Super (context);
  Initview (); } public Countdownbutton (context Context, AttributeSet attrs) {Super (context, attrs);
  Initview (); Countdownbutton (context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, Defstyleatt
    R);
  Initview (); /** * Initialization operation */private void Initview () {if (!
    Textutils.isempty (GetText ())) {Beforetext = GetText (). toString (). Trim ();
    } this.settext (Beforetext);
  Setonclicklistener (this);
    /** * Initialization time */private void Inittimer () {timer = new timer ();
      TimerTask = new TimerTask () {@Override public void run () {handler.sendemptymessage (1);
  }
    };
  /** * Set Countdown length * * @param length default millisecond */public void SetLength (long length) {this.length = length; /** * Set the text displayed when not clicked * * @param beforetext/public void Setbeforetext (String beforetext) {this.be
  Foretext = Beforetext; /** * Set the text to be displayed without clicking * * @param beforetext/public void Setaftertext (StrinG beforetext) {this.aftertext = Aftertext; /** * Set Listener button click event * * @param onclicklistener/@Override public void Setonclicklistener (Onclicklisten Er onclicklistener) {if (Onclicklistener instanceof Countdownbutton) {Super.setonclicklistener (OnclickListener
    );
    else {this.onclicklistener = Onclicklistener;
    }/** * Click the button after the operation * * @param v * * * @Override public void OnClick (View v) {start ();
    if (Onclicklistener!= null) {Onclicklistener.onclick (v);
    }/** * Start countdown * * public void Start () {Inittimer ();
    This.settext (length/1000 + aftertext);
    This.setenabled (FALSE);
  Timer.schedule (timertask, 0, 1000); /** * Update displayed text/private Handler Handler = new Handler () {@Override public void Handlemessage (Messa
      GE msg) {super.handlemessage (msg);
      CountdownButton.this.setText (length/1000 + aftertext);
      length = 1000; if (Length < 0) {CountdownButton.this.setEnabled (true);
        CountdownButton.this.setText (Beforetext);
        Cleartimer ();
      Length = 60 * 1000;

  }
    }
  };
      /** * Clear Countdown */private void Cleartimer () {if (timertask!= null) {timertask.cancel ();
    TimerTask = null;
      } if (timer!= null) {timer.cancel ();
    timer = null; }/** * Remember to clear the countdown when the activity or fragment dies, * Because if the countdown is not finished, the child thread is still running, * This will cause memory overflow/@Override prote
    CTED void Ondetachedfromwindow () {Cleartimer ();
  Super.ondetachedfromwindow ();

 }
}

5. Use , super simple

 <com.bm.ykzx.view.countdownbutton
        android:id= "@+id/cdb_register_timer"
        android:layout_width= "120DP"
        android:textallcaps= "false"
        android:layout_height= "match_parent"
        android:background= "@android: Color/transparent "
        android:gravity=" center "
        android:paddingleft=" 3DP "
        android:paddingright=" 3DP "
        android:text= "Get Authentication Code"
        android:textcolor= "#1179c4"
        android:textsize= "@dimen/txt14sp"/>

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.

Related Article

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.