Android 自定义View_方框验证码

Android 自定义View之方框验证码

Gihub项目

  • 最近项目有一个需求,6个方框的验证码,要求不能出现光标,然后删除键一个个删除,输入完成会回调。


    效果图.gif

  • 刚开始做这个自定义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

继承与RelativeLayout,构造方法选1-3个参数的,顺便定义好要用的参数。

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

这里需要一个LinearLayout来作为这些TextView的容器,当然你也可以不用LinearLayout,父布局用ConstraintLayout一个就能实现。

/**
 * 设置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

这个EditText设置的跟父容器一样的大,方便我们点击这个自定义View就能弹起键小盘,光闭光标,背景设置空白。每一位数字写下后,就将下一位的TextView设为焦点。

/**
 * 输入框和父布局一样大,但字体大小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.加上输入完成回调

在写EditText的时候,afterTextChanged里加入回调。在构造方法里加入初始化的代码,就可以了。

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.用上自定义的参数

到这运行一下,基本可以显示出来,但是为了更灵活的使用嘛,我们之前写的attr就用上了。获取参数,初始化即可。

<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();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,043评论 25 707
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,650评论 2 59
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,960评论 3 119
  • 无论我和他们讨论什么 他们都和我谈钱 他们让我鄙视 我让他们可怜 我以为有些快乐 在于内心深处 我以为有些生活 超...
    更向远行阅读 125评论 0 1
  • 愿做矗立的灯塔一座, 因为曾经被这样的光明指引; 愿做炽热的炉火一团, 因为曾经被这样的光热温暖; 愿做肥沃的土地...
    塵光阅读 353评论 3 4