Android實現(xiàn)方框驗證碼功能

剛開始做這個自定義view,我是想著用多個EditText來實現(xiàn)功能,做到后面發(fā)現(xiàn)在獲取焦點這個問題上,多個EditText處理不了,于是上網(wǎng)看了別的思路,就是用多個TextView顯示,但是輸入的EditText只有一個,我覺得這個思路可行,自己再次動手改代碼。
具體:這個View就是繼承與RelativeLayout,然后里面有一個LinearLayout,水平排列放下6個TextView,最后在LinearLayout上蓋上一個字體大小為0的EditText。
EditText做監(jiān)聽,將內(nèi)容賦值給每一個TextView。
1、設想哪些值是可變的:
②驗證碼的字體顏色
③驗證碼框的寬度
④驗證碼框的高度
⑤驗證碼框的默認背景
⑥驗證碼框的焦點背景
⑦驗證碼框之間的間距
⑧驗證碼的個數(shù)
然后在res/values/下創(chuàng)建一個attr.xml,用于存放這些參數(shù)。
<?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、創(chuàng)建自定義View
public class VerificationCodeView extends RelativeLayout {//輸入的長度private int vCodeLength = 6;//輸入的內(nèi)容private String inputData;private EditText editText;//TextView的listprivate 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);//內(nèi)容居中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不需要marginif (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)});//輸入類型為數(shù)字editText.setInputType(InputType.TYPE_CLASS_NUMBER);editText.setTextSize(0);editText.setBackgroundResource(0);editText.addTextChangedListener(new TextWatcher() {@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}@Overridepublic 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設置數(shù)據(jù)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("");}}}@Overridepublic 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、用上自定義的參數(shù)
<com.wuyanhua.verificationcodeview.VerificationCodeViewandroid: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評論
圖片
表情
