1. 程式人生 > >自定義驗證碼輸入框

自定義驗證碼輸入框

由於看到滴滴打車的輸入驗證碼的效果挺好的,就想著自己實現一個,先上一個效果圖,

實現了基本的功能,下面的是主要類

package com.example.mengsong.verificationcode;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by MengSong on 2016/11/27.
 */
public class Code extends LinearLayout implements TextWatcher, View.OnKeyListener {
    //驗證碼的位數
    private int codeNumber;
    //兩個驗證碼之間的距離
    private int codeSpace;
    //驗證碼邊框的邊長
    private int lengthSide;
    //驗證碼的大小
    private float textSize;
    //字型顏色
    private int textColor = Color.BLACK;

    private int inputType = 2;

    private LinearLayout.LayoutParams mEditparams;

    private LinearLayout.LayoutParams mViewparams;

    private Context mContext;

    private List<EditText> mEditTextList = new ArrayList<>();

    private int currentPosition = 0;

    public Code(Context context) {
        super(context);
    }

    public Code(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.code);
        codeNumber = typedArray.getInteger(R.styleable.code_codeNumber, 6);
        codeSpace = typedArray.getInteger(R.styleable.code_codeSpace, 20);
        lengthSide = typedArray.getInteger(R.styleable.code_lengthSide, 50);
        textSize = typedArray.getFloat(R.styleable.code_textSize, 20);
        inputType = typedArray.getInteger(R.styleable.code_inputType, 2);
        mEditparams = new LinearLayout.LayoutParams(lengthSide, lengthSide);
        mViewparams = new LinearLayout.LayoutParams(codeSpace, lengthSide);
        initView();
    }

    /**
     * 初始化輸入框
      */
    private void initView() {
        for (int i = 0; i < codeNumber; i++) {
            EditText editText = new EditText(mContext);
            editText.setCursorVisible(false);
            editText.setOnKeyListener(this);
            editText.setTextSize(textSize);
            editText.setInputType(inputType);
            editText.setTextColor(textColor);
            editText.setPadding(0, 0, 0, 0);
            editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1)});
            editText.addTextChangedListener(this);
            editText.setLayoutParams(mEditparams);
            editText.setGravity(Gravity.CENTER);
            editText.setBackgroundResource(R.drawable.shape_edit);
            addView(editText);
            mEditTextList.add(editText);
            if (i != codeNumber - 1) {
                View view = new View(mContext);
                view.setLayoutParams(mViewparams);
                addView(view);
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        if (i == 0 && i2 >= 1 && currentPosition != mEditTextList.size() - 1) {
            currentPosition++;
            mEditTextList.get(currentPosition).requestFocus();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }

    /**
     * 監聽刪除鍵
     * @param view
     * @param i
     * @param keyEvent
     * @return
     */
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        EditText editText = (EditText) view;
        if (i == KeyEvent.KEYCODE_DEL && editText.getText().length() == 0) {
            int action = keyEvent.getAction();
            if (currentPosition != 0 && action == KeyEvent.ACTION_DOWN) {
                currentPosition--;
                mEditTextList.get(currentPosition).requestFocus();
                mEditTextList.get(currentPosition).setText("");
            }
        }
        return false;
    }

    /**
     * 獲取驗證碼
     * @return
     */
    public String getVerificationCode() {
        StringBuffer stringBuffer = new StringBuffer();
        for (EditText string : mEditTextList) {
            stringBuffer.append(string.getText().toString());
        }
        return stringBuffer.toString();
    }
}

使用方法,直接在佈局中使用我的佈局是
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" tools:context="com.example.mengsong.verificationcode.MainActivity"> <com.example.mengsong.verificationcode.Code android:layout_marginTop="30dp" android:id="@+id/code" android:gravity="center" android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_centerInParent="true" 驗證碼位數   app:codeNumber="6" 驗證碼之間的距離 app:codeSpace="20" 輸入型別,可以到InputType中查詢對應的數字   app:inputType="2" 驗證碼框邊長   app:lengthSide="60" 驗證碼字型大小   app:textSize="20" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="show" /> </LinearLayout> attr檔案的程式碼如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="code">
        <attr name="codeNumber" format="integer"/>
        <attr name="codeSpace" format="integer"/>
        <attr name="lengthSide" format="integer"/>
        <attr name="textSize" format="float"/>
        <attr name="inputType" format="integer"/>
    </declare-styleable>
</resources>
原始碼我已經分享到百度網盤下載地址:http://pan.baidu.com/s/1nuQonhv
分享是最好的學習