Android(安卓)自定义发送验证码, 倒计时
16lz
2021-01-26
在开发时, 经常会写获取验证码倒计时这个控件, 因为刚接手别人的项目, 发现该项目中使用的控件有问题, 于是自己写了个
思路: 在button内实现onClick方法, 在onClick内处理倒计时等事情
效果图:
布局代码:
activity代码:
view代码:
public class IdentifyingCodeButton extends android.support.v7.widget.AppCompatButton { private Handler handler; private int time; private Drawable canClickBackground;//可点击的时候背景 private Drawable cannotClickBackground;//不可点击的时候背景 private String defaultText;//默认文字 private int canClickTextColor = -1;//可点击时文字颜色 private int cannottClickTextColor = -1;//不可可点击时文字颜色 private int countTime = 60; public IdentifyingCodeButton(Context context) { this(context,null); } public IdentifyingCodeButton(Context context, AttributeSet attrs) { this(context,attrs,0); } public IdentifyingCodeButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); handler = new Handler(){ @Override public void handleMessage(Message msg) { countDown(); } }; defaultText = this.getText().toString().trim(); if (defaultText == null || defaultText.length() == 0){ defaultText = "获取验证码"; this.setText(defaultText); } this.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { time = countTime; handler.sendEmptyMessage(0); } }); } private void countDown(){ time--; if (time != 0){ this.setText(time + "秒"); this.setClickable(false); if (cannotClickBackground == null){ this.setBackgroundColor(Color.GRAY); }else{ this.setBackground(cannotClickBackground); } if (cannottClickTextColor != -1){ this.setTextColor(cannottClickTextColor); } handler.sendEmptyMessageDelayed(0,1000); }else{ this.setClickable(true); this.setText(defaultText); if (canClickBackground != null) this.setBackground(canClickBackground); if (canClickTextColor != -1){ this.setTextColor(canClickTextColor); } } } //设置倒计时时长 默认60秒 public void setTime(int time){ this.time = time; this.countTime = time; } public void setCannotClickBackground(Drawable cannotClickBackground){ this.cannotClickBackground = cannotClickBackground; } public void setCanClickBackground(Drawable canClickBackground){ this.canClickBackground = canClickBackground; } public void setCanClickTextColor(int canClickTextColor) { this.canClickTextColor = canClickTextColor; } public void setCannottClickTextColor(int cannottClickTextColor) { this.cannottClickTextColor = cannottClickTextColor; }}
原理很简单, 不同情况使用可以再修改完善
更多相关文章
- WakeLock使用方法示例代码
- [代码片段] 【转】Android以最省内存的方式读取本地资源的
- Android通过LIstView显示文件列表的两种方法介绍
- GLSurfaceView 基本使用与源码解析
- android模仿移动MM Tab 点击 背景 滑动效果
- android 自动化测试之MonkeyRunner学习(二)
- 【Java&Android开源库代码剖析】のAndroid-Universal-Image-Load
- android2.3修改ethernet默认为不选中状态
- 【Android(安卓)Native Code开发系列】六 一个Native Service的