Android实现方框验证码功能
龙旋
共 10290字,需浏览 21分钟
· 2022-09-17
刚开始做这个自定义view,我是想着用多个EditText来实现功能,做到后面发现在获取焦点这个问题上,多个EditText处理不了,于是上网看了别的思路,就是用多个TextView显示,但是输入的EditText只有一个,我觉得这个思路可行,自己再次动手改代码。
具体:这个View就是继承与RelativeLayout,然后里面有一个LinearLayout,水平排列放下6个TextView,最后在LinearLayout上盖上一个字体大小为0的EditText。
EditText做监听,将内容赋值给每一个TextView。
1、设想哪些值是可变的:
②验证码的字体颜色
③验证码框的宽度
④验证码框的高度
⑤验证码框的默认背景
⑥验证码框的焦点背景
⑦验证码框之间的间距
⑧验证码的个数
然后在res/values/下创建一个attr.xml,用于存放这些参数。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="VerificationCodeView">
<!-- 验证码长度 -->
<attr name="vCodeDataLength" format="integer" />
<!-- 验证码字体大小 -->
<attr name="vCodeTextSize" format="dimension" />
<!-- 验证码字体颜色 -->
<attr name="vCodeTextColor" format="color" />
<!-- 验证码框的宽度 -->
<attr name="vCodeWidth" format="dimension" />
<!-- 验证码框的高度 -->
<attr name="vCodeHeight" format="dimension" />
<!-- 验证码框间距 -->
<attr name="vCodeMargin" format="dimension" />
<!-- 验证码默认背景 -->
<attr name="vCodeBackgroundNormal" format="reference" />
<!-- 验证码焦点背景 -->
<attr name="vCodeBackgroundFocus" format="reference" />
</declare-styleable>
</resources>
2、用shape画两个背景框:
在drawable下画出两个即可
?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/white"/>
<stroke android:color="@color/grey"
android:width="1dp"/>
</shape>
3、创建自定义View
public class VerificationCodeView extends RelativeLayout {
//输入的长度
private int vCodeLength = 6;
//输入的内容
private String inputData;
private EditText editText;
//TextView的list
private List<TextView> tvList = new ArrayList<>();
//输入框默认背景
private int tvBgNormal = R.drawable.verification_code_et_bg_normal;
//输入框焦点背景
private int tvBgFocus = R.drawable.verification_code_et_bg_focus;
//输入框的间距
private int tvMarginRight = 10;
//TextView宽
private int tvWidth = 45;
//TextView高
private int tvHeight = 45;
//TextView字体颜色
private int tvTextColor;
//TextView字体大小
private float tvTextSize = 8;
public VerificationCodeView(Context context) {
this(context, null);
}
public VerificationCodeView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VerificationCodeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
4、初始化里面的TextView
/**
* 设置TextView
*/
private void initTextView() {
LinearLayout linearLayout = new LinearLayout(getContext());
addView(linearLayout);
LayoutParams llLayoutParams = (LayoutParams) linearLayout.getLayoutParams();
llLayoutParams.width = LayoutParams.MATCH_PARENT;
llLayoutParams.height = LayoutParams.WRAP_CONTENT;
//linearLayout.setLayoutParams(llLayoutParams);
//水平排列
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
//内容居中
linearLayout.setGravity(Gravity.CENTER);
for (int i = 0; i < vCodeLength; i++) {
TextView textView = new TextView(getContext());
linearLayout.addView(textView);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
layoutParams.width = tvWidth;
layoutParams.height = tvHeight;
//只需将中间隔开,所以最后一个textView不需要margin
if (i == vCodeLength - 1) {
layoutParams.rightMargin = 0;
} else {
layoutParams.rightMargin = tvMarginRight;
}
//textView.setLayoutParams(layoutParams);
textView.setBackgroundResource(tvBgNormal);
textView.setGravity(Gravity.CENTER);
//注意单位
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,tvTextSize);
textView.setTextColor(tvTextColor);
tvList.add(textView);
}
}
5、加入EditText
/**
* 输入框和父布局一样大,但字体大小0,看不见的
*/
private void initEditText() {
editText = new EditText(getContext());
addView(editText);
LayoutParams layoutParams = (LayoutParams) editText.getLayoutParams();
layoutParams.width = layoutParams.MATCH_PARENT;
layoutParams.height = tvHeight;
editText.setLayoutParams(layoutParams);
//防止横盘小键盘全屏显示
editText.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN);
//隐藏光标
editText.setCursorVisible(false);
//最大输入长度
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(vCodeLength)});
//输入类型为数字
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setTextSize(0);
editText.setBackgroundResource(0);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s != null && !TextUtils.isEmpty(s.toString())) {
//有验证码的情况
inputData = s.toString();
//如果是最后一位验证码,焦点在最后一个,否者在下一位
if (inputData.length() == vCodeLength) {
tvSetFocus(vCodeLength - 1);
} else {
tvSetFocus(inputData.length());
}
//给textView设置数据
for (int i = 0; i < inputData.length(); i++) {
tvList.get(i).setText(inputData.substring(i, i + 1));
}
for (int i = inputData.length(); i < vCodeLength; i++) {
tvList.get(i).setText("");
}
} else {
//一位验证码都没有的情况
tvSetFocus(0);
for (int i = 0; i < vCodeLength; i++) {
tvList.get(i).setText("");
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (null != onVerificationCodeCompleteListener) {
if (s.length() == vCodeLength) {
onVerificationCodeCompleteListener.verificationCodeComplete(s.toString());
} else {
onVerificationCodeCompleteListener.verificationCodeIncomplete(s.toString());
}
}
}
});
}
/**
* 假装获取焦点
*/
private void tvSetFocus(int index) {
tvSetFocus(tvList.get(index));
}
private void tvSetFocus(TextView textView) {
for (int i = 0; i < vCodeLength; i++) {
tvList.get(i).setBackgroundResource(tvBgNormal);
}
//重新获取焦点
textView.setBackgroundResource(tvBgFocus);
}
6、加上输入完成回调
public VerificationCodeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
initTextView();
initEditText();
tvSetFocus(0);
}
/**
* 输入完成回调接口
*/
public interface OnVerificationCodeCompleteListener {
void verificationCodeComplete(String verificationCode);
}
public void setOnVerificationCodeCompleteListener(OnVerificationCodeCompleteListener onVerificationCodeCompleteListener) {
this.onVerificationCodeCompleteListener = onVerificationCodeCompleteListener;
}
7、用上自定义的参数
<com.wuyanhua.verificationcodeview.VerificationCodeView
android:id="@+id/verificationCodeView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:paddingTop="20dp"
app:vCodeBackgroundFocus="@drawable/verification_code_et_bg_focus"
app:vCodeBackgroundNormal="@drawable/verification_code_et_bg_normal"
app:vCodeDataLength="6"
app:vCodeHeight="45dp"
app:vCodeMargin="10dp"
app:vCodeTextColor="@color/black"
app:vCodeTextSize="8sp"
app:vCodeWidth="45dp" />
public VerificationCodeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//获取自定义样式的属性
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.VerificationCodeView, defStyleAttr, 0);
for (int i = 0; i < typedArray.getIndexCount(); i++) {
int attr = typedArray.getIndex(i);
if (attr == R.styleable.VerificationCodeView_vCodeDataLength) {
//验证码长度
vCodeLength = typedArray.getInteger(attr, 6);
} else if (attr == R.styleable.VerificationCodeView_vCodeTextColor) {
//验证码字体颜色
tvTextColor = typedArray.getColor(attr, Color.BLACK);
} else if (attr == R.styleable.VerificationCodeView_vCodeTextSize) {
//验证码字体大小
tvTextSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 8, getResources().getDisplayMetrics()));
} else if (attr == R.styleable.VerificationCodeView_vCodeWidth) {
//方框宽度
tvWidth = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics()));
} else if (attr == R.styleable.VerificationCodeView_vCodeHeight) {
//方框宽度
tvHeight = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,45,getResources().getDisplayMetrics()));
}else if(attr == R.styleable.VerificationCodeView_vCodeMargin){
//方框间隔
tvMarginRight = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10,getResources().getDisplayMetrics()));
}else if(attr == R.styleable.VerificationCodeView_vCodeBackgroundNormal){
//默认背景
tvBgNormal = typedArray.getResourceId(attr,R.drawable.verification_code_et_bg_normal);
}else if(attr == R.styleable.VerificationCodeView_vCodeBackgroundFocus){
//焦点背景
tvBgFocus = typedArray.getResourceId(attr,R.drawable.verification_code_et_bg_focus);
}
}
//用完回收
typedArray.recycle();
init();
}
https://github.com/Goodbao/VerificaitionCodeView
评论
知乎高问:程序员有必要知道为什么做某个功能吗?
将Python客栈设为“星标⭐”第一时间收到最新资讯前言知乎上有一个提问:程序员有必要知道为什么做某个功能吗?↓↓↓今天,我们就这个话题一起来做个讨论。不知道程序员的你,在接到产品经理提的一个需求后,是习惯马上动手开始撸代码呢?还是会先暂停一下,认真思考一会如下一些问题,比如这个需求产生的背景是什么
Python客栈
0
盘点一个使用超级鹰识别验证码并自动登录的案例
点击上方“Python共享之家”,进行关注回复“资源”即可获赠Python学习资料今日鸡汤江上几人在,天涯孤棹还。大家好,我是皮皮。一、前言前几天在Python钻石交流群【静惜】问了一个Python实现识别验证码并自动登录的问题,提问截图如下:验证码的截图如下所示:二、实现过程这里大家激烈的探讨,【
IT共享之家
0
SpringBoot+Minio实现上传凭证、分片上传、秒传和断点续传
关注我们,设为星标,每天7:40不见不散,架构路上与您共享回复架构师获取资源大家好,我是你们的朋友架构君,一个会写代码吟诗的架构师。Spring Boot整合Minio后,前端的文件上传有两种方式:1、文件上传到后端,由后端保存到Minio这种方式好处是完全由后端集中管理,可以很好的做到、身份验证、
Java架构师社区
0
超越原生,散点图实现华夫饼图
之前我们介绍过了如何使用新卡片图实现华夫饼图。参考:超越原生,PowerBI 华夫饼图实现但是利用卡片图实现的华夫饼图有一些缺点,形状之间的大小跟间距不太好把握,而且有时形状大一点的话显示就会不正常,需要做出二次调整。今天给大家介绍一种原生视觉对象生成华夫饼图的更佳方案,既简单又美观。上图是利用散点
PowerBI战友联盟
2
Spring Boot + flowable 快速实现工作流
关注我们,设为星标,每天7:40不见不散,架构路上与您共享回复架构师获取资源大家好,我是你们的朋友架构君,一个会写代码吟诗的架构师。来源:blog.csdn.net/zhan107876/article/details/120815560总览一、flowable-ui部署运行二、绘制流程图绘图细节:
Java架构师社区
0
实现订单30分钟自动取消的策略
原文:juejin.cn/post/7285167401821798400简介在电商和其他涉及到在线支付的应用中,通常需要实现一个功能:如果用户在生成订单后的一定时间内未完成支付,系统将自动取消该订单。本文将详细介绍基于Spring Boot框架实现订单30分钟内未支付自动取消的几种方案,并提供实例
JAVA乐园
0
AI大模型之路 第三篇:从零实现词嵌入模型,加深理解!
你好,我是郭震今天我们研究「AI大模型第三篇」:词维度预测,很多读者听过词嵌入,这篇文章解答下面问题:词嵌入是什么意思?怎么做到的?原理是什么?从零实现一个专属你数据集的词嵌入我们完整从零走一遍,根基的东西要理解透,这样才能发明出更好的东西。1 skip-gram模型Skip-gram模型是一种广泛
Python与算法社区
11
从理解路由到实现一套Router(路由)
大厂技术 高级前端 Node进阶点击上方 程序员成长指北,关注公众号回复1,加入高级Node交流群平时在Vue项目中经常用到路由,但是也仅仅处于会用的层面,很多基础知识并不是真正的理解。于是就趁着十一”小长假“查阅了很多资料,总结下路由相关的知识
程序员成长指北
347