手机注册一般都会有一个按钮,默认显示获取验证码,点击之后变成xx秒之后重新获取验证码

在网上查到有两种方法可以实现这种功能,一种是自定义一个timeButton,另外一种是利用封装好的60秒获取验证码工具类

第一种,首先在App.java类中添加一行代码

public static Map<String, Long> map;//用来存放倒计时的时间

然后将TimeButton类加入到工程中,时间默认是60s,也可以随后通过set方法,在代码中修改

package net.zhomi.negotiation.view.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask; import net.zhomi.negotiation.app.App; import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; public class TimeButton extends Button implements OnClickListener {
private long lenght = 60 * 1000;// 倒计时长度,这里给了默认60秒
private String textafter = "秒后重新获取";
private String textbefore = "点击获取验证码";
private final String TIME = "time";
private final String CTIME = "ctime";
private OnClickListener mOnclickListener;
private Timer t;
private TimerTask tt;
private long time;
private Context mContext;
Map<String, Long> map = new HashMap<String, Long>(); public TimeButton(Context context) {
super(context);
setOnClickListener(this); } public TimeButton(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setOnClickListener(this);
} @SuppressLint("HandlerLeak")
Handler han = new Handler() {
public void handleMessage(android.os.Message msg) {
TimeButton.this.setText(time / 1000 + textafter);
time -= 1000;
if (time < 0) {
TimeButton.this.setEnabled(true);
TimeButton.this.setText(textbefore);
clearTimer();
}
};
}; private void initTimer() {
time = lenght;
t = new Timer();
tt = new TimerTask() { @Override
public void run() {
Log.e("yung", time / 1000 + "");
han.sendEmptyMessage(0x01);
}
};
} private void clearTimer() {
Toast.makeText(mContext, "计时结束", Toast.LENGTH_SHORT).show();
if (tt != null) {
tt.cancel();
tt = null;
}
if (t != null)
t.cancel();
t = null;
} @Override
public void setOnClickListener(OnClickListener l) {
if (l instanceof TimeButton) {
super.setOnClickListener(l);
} else
this.mOnclickListener = l;
} @Override
public void onClick(View v) {
if (mOnclickListener != null)
mOnclickListener.onClick(v);
initTimer();
this.setText(time / 1000 + textafter);
this.setEnabled(false);
t.schedule(tt, 0, 1000);
// t.scheduleAtFixedRate(task, delay, period);
} /**
* 和activity的onDestroy()方法同步
*/
public void onDestroy() {
if (App.map == null)
App.map = new HashMap<String, Long>();
App.map.put(TIME, time);
App.map.put(CTIME, System.currentTimeMillis());
clearTimer();
Log.e("yung", "onDestroy");
} /**
* 和activity的onCreate()方法同步
*/
public void onCreate(Bundle bundle) {
Log.e("yung", App.map + "");
if (App.map == null)
return;
if (App.map.size() <= 0)// 这里表示没有上次未完成的计时
return;
long time = System.currentTimeMillis() - App.map.get(CTIME)
- App.map.get(TIME);
App.map.clear();
if (time > 0)
return;
else {
initTimer();
this.time = Math.abs(time);
t.schedule(tt, 0, 1000);
this.setText(time + textafter);
this.setEnabled(false);
}
} /** * 设置计时时候显示的文本 */
public TimeButton setTextAfter(String text1) {
this.textafter = text1;
return this;
} /** * 设置点击之前的文本 */
public TimeButton setTextBefore(String text0) {
this.textbefore = text0;
this.setText(textbefore);
return this;
} /**
* 设置到计时长度
*
* @param lenght
* 时间 默认毫秒
* @return
*/
public TimeButton setLenght(long lenght) {
this.lenght = lenght;
return this;
}
/* *
*/
}

TimeButton在资源文件中的使用与Button并没有太大的不同

<net.zhomi.negotiation.view.utils.TimeButton//TimeButton所在的包
android:id="@+id/btn_getcode"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginRight="15dp"
android:layout_weight="2"
android:background="@null"
android:singleLine="true"
android:text="60秒后重新获取"
android:textColor="@color/balck"
android:textSize="@dimen/normal_text_size" />

第二种

首先看封装的工具类

package com.example.timebtn;

import android.os.CountDownTimer;
import android.widget.Button; public class TimerCount extends CountDownTimer {
private Button bnt; public TimerCount(long millisInFuture, long countDownInterval, Button bnt) {
super(millisInFuture, countDownInterval);
this.bnt = bnt;
} public TimerCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
} @Override
public void onFinish() {
// TODO Auto-generated method stub
bnt.setClickable(true);
bnt.setText("获取验证码");
} @Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
bnt.setClickable(false);
bnt.setText(arg0 / 1000 + "秒后重新获取");
}
}

如何使用:

Button btn = (Button) findViewById(R.id.button1);
TimerCount timer = new TimerCount(60000, 1000, btn);
timer.start();

看起来第二种的代码更简单,但是还是建议用第一种。

【实习项目记录】(四)Android 实现手机验证时,按钮倒计时60s的更多相关文章

  1. js手机短信按钮倒计时

    /*   120秒手机短信按钮倒计时   */    exports.sendmessage = function (name) {        var second = 120; $(name). ...

  2. opencv 手写选择题阅卷 (四)Android端 手机应用开发

    opencv 手写选择题阅卷 (四)Android 手机应用开发 在PC端把代码调通以后开始开发Android 手机应用,因为主要功能代码为C++代码,所以需要通过NDK编译,JAVA通过JNI方式调 ...

  3. 【边做项目边学Android】手机安全卫士05_2:程序主界面,为每一个条目加入事件

    为每一个条目加入点击事件监听器 gv_main.setOnItemClickListener(this); 须要当前Activity实现OnItemClickListener接口.同一时候实现publ ...

  4. 【实习项目记录】(一)加密算法MD5和RSA

    什么是md5加密? MD5的全称是Message-Digest Algorithm 5(信息-摘要算法),在90年代初由MIT Laboratory for Computer Science和RSA ...

  5. IOS客户端Coding项目记录(四)

    1:打开Xcode,然后闪退,报加载某库出现异常 如/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolc ...

  6. 【实习项目记录】(二) JSON

    介绍 JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 易于人阅读和编写.同时也易于机器解析和生成. 它基于JavaScript Program ...

  7. 手机验证 发送验证码倒计时js

    html: <input name="Tel" class="weui-input" type="tel" placeholder=& ...

  8. android 利用CountDownTimer实现时分秒倒计时效果

    https://blog.csdn.net/mrzhao_perfectcode/article/details/81289578

  9. WPF 手机验证码 发送按钮倒计时 代码

    private async void SendButton_Click(object sender, RoutedEventArgs e) { var button = sender as Butto ...

随机推荐

  1. LeetCode 362. Design Hit Counter

    原题链接在这里:https://leetcode.com/problems/design-hit-counter/description/ 题目: Design a hit counter which ...

  2. ERR_PTR PTR_ERR IS_ERR ERROR

    在linux-x.xx/include/uapi/asm-generic/errno-base.h和errno.h里分别定义了返回错误的信息. errno-base.h: #ifndef _ASM_G ...

  3. POJ1733:Parity game

    浅谈并查集:https://www.cnblogs.com/AKMer/p/10360090.html 题目传送门:http://poj.org/problem?id=1733 带权并查集裸题.区间和 ...

  4. bzoj 3328 PYXFIB —— 单位根反演

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3328 单位根反演,主要用到了 \( [k|n] = \frac{1}{k} \sum\lim ...

  5. 第一章计算机网络和因特网-day01

    什么是因特网: 其一:构成因特网的基本硬件与软件. 其二:为分布式应用提供服务的联网基础设施. 终端机器称为主机( host ) 或者端系统( end system ) 端系统通过通信链路(commu ...

  6. lrzsz-串口传输文件

    二.编译安装 1.解压文件,进入目录     tar –zxvf lrzsz-0.12.20.tar.bz        cd / lrzsz-0.12.20 ./configure  2../con ...

  7. Spring 自动注册及自动装配

    Spring支持三种注册Bean及装配Bean的方式: 显式地在Java代码中注册及装配 显示地在Xml文件中注册及装配 隐式地装配,即自动注册及装配 这三种方式可以混合使用.选择哪种更多地是看个人品 ...

  8. Oracle OCM提纲

    ocm提纲 数据库创建详解 ◆ 通过手动方式创建数据库 环境变量的设置 密码文件的创建过程以及使用情景 Oracle数据库中参数文件的演进过程 参数文件的对比 参数的修改方式介绍 数据库启动过程时的内 ...

  9. Python No module named pkg_resources

    好记性不如烂笔头. I encountered the same ImportError today while trying to use pip. Somehow the setuptools p ...

  10. Python多进程-进程池

    进程池可以减轻多进程对CPU的负担 把一个进程序列放入进程池,使用的时候,就会在进程池中取进程如果进程池中没有进程了,脚本就会等待,直到进程池中有可用进程 进程池生成的子线程,不能直接运行,要放入进程 ...