1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

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

        共 10290字,需瀏覽 21分鐘

         ·

        2022-09-17 17:03

        最近項(xiàng)目有一個(gè)需求,6個(gè)方框的驗(yàn)證碼,要求不能出現(xiàn)光標(biāo),然后刪除鍵一個(gè)個(gè)刪除,輸入完成會(huì)回調(diào)。


        • 剛開(kāi)始做這個(gè)自定義view,我是想著用多個(gè)EditText來(lái)實(shí)現(xiàn)功能,做到后面發(fā)現(xiàn)在獲取焦點(diǎn)這個(gè)問(wèn)題上,多個(gè)EditText處理不了,于是上網(wǎng)看了別的思路,就是用多個(gè)TextView顯示,但是輸入的EditText只有一個(gè),我覺(jué)得這個(gè)思路可行,自己再次動(dòng)手改代碼。


        • 具體:這個(gè)View就是繼承與RelativeLayout,然后里面有一個(gè)LinearLayout,水平排列放下6個(gè)TextView,最后在LinearLayout上蓋上一個(gè)字體大小為0的EditText。


          EditText做監(jiān)聽(tīng),將內(nèi)容賦值給每一個(gè)TextView。


        1、設(shè)想哪些值是可變的:

        ①驗(yàn)證碼的字體大小
        ②驗(yàn)證碼的字體顏色
        ③驗(yàn)證碼框的寬度
        ④驗(yàn)證碼框的高度
        ⑤驗(yàn)證碼框的默認(rèn)背景
        ⑥驗(yàn)證碼框的焦點(diǎn)背景
        ⑦驗(yàn)證碼框之間的間距
        ⑧驗(yàn)證碼的個(gè)數(shù)
        • 然后在res/values/下創(chuàng)建一個(gè)attr.xml,用于存放這些參數(shù)。

        <?xml version="1.0" encoding="utf-8"?><resources>
        <declare-styleable name="VerificationCodeView"> <!-- 驗(yàn)證碼長(zhǎng)度 --> <attr name="vCodeDataLength" format="integer" /> <!-- 驗(yàn)證碼字體大小 --> <attr name="vCodeTextSize" format="dimension" /> <!-- 驗(yàn)證碼字體顏色 --> <attr name="vCodeTextColor" format="color" /> <!-- 驗(yàn)證碼框的寬度 --> <attr name="vCodeWidth" format="dimension" /> <!-- 驗(yàn)證碼框的高度 --> <attr name="vCodeHeight" format="dimension" /> <!-- 驗(yàn)證碼框間距 --> <attr name="vCodeMargin" format="dimension" /> <!-- 驗(yàn)證碼默認(rèn)背景 --> <attr name="vCodeBackgroundNormal" format="reference" /> <!-- 驗(yàn)證碼焦點(diǎn)背景 --> <attr name="vCodeBackgroundFocus" format="reference" /> </declare-styleable>
        </resources>

        2、用shape畫(huà)兩個(gè)背景框:

        一個(gè)默認(rèn)樣式,一個(gè)焦點(diǎn)位置,我寫(xiě)的框是一樣樣的,就是顏色不一樣。
        • 在drawable下畫(huà)出兩個(gè)即可

        ?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

        繼承與RelativeLayout,構(gòu)造方法選1-3個(gè)參數(shù)的,順便定義好要用的參數(shù)。
        public class VerificationCodeView extends RelativeLayout {    //輸入的長(zhǎng)度    private int vCodeLength = 6;    //輸入的內(nèi)容    private String inputData;    private EditText editText;
        //TextView的list private List<TextView> tvList = new ArrayList<>(); //輸入框默認(rèn)背景 private int tvBgNormal = R.drawable.verification_code_et_bg_normal; //輸入框焦點(diǎn)背景 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

        這里需要一個(gè)LinearLayout來(lái)作為這些TextView的容器,當(dāng)然你也可以不用LinearLayout,父布局用ConstraintLayout一個(gè)就能實(shí)現(xiàn)。
        /** * 設(shè)置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; //只需將中間隔開(kāi),所以最后一個(gè)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

        這個(gè)EditText設(shè)置的跟父容器一樣的大,方便我們點(diǎn)擊這個(gè)自定義View就能彈起鍵小盤(pán),光閉光標(biāo),背景設(shè)置空白。每一位數(shù)字寫(xiě)下后,就將下一位的TextView設(shè)為焦點(diǎn)。
        /** * 輸入框和父布局一樣大,但字體大小0,看不見(jiàn)的 */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);
        //防止橫盤(pán)小鍵盤(pán)全屏顯示 editText.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN); //隱藏光標(biāo) editText.setCursorVisible(false); //最大輸入長(zhǎng)度 editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(vCodeLength)}); //輸入類(lèi)型為數(shù)字 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())) { //有驗(yàn)證碼的情況 inputData = s.toString();
        //如果是最后一位驗(yàn)證碼,焦點(diǎn)在最后一個(gè),否者在下一位 if (inputData.length() == vCodeLength) { tvSetFocus(vCodeLength - 1); } else { tvSetFocus(inputData.length()); }
        //給textView設(shè)置數(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 { //一位驗(yàn)證碼都沒(méi)有的情況 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()); } } } });}
        /** * 假裝獲取焦點(diǎn) */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); } //重新獲取焦點(diǎn) textView.setBackgroundResource(tvBgFocus);}

        6、加上輸入完成回調(diào)

        在寫(xiě)EditText的時(shí)候,afterTextChanged里加入回調(diào)。在構(gòu)造方法里加入初始化的代碼,就可以了。
        public VerificationCodeView(Context context, AttributeSet attrs, int defStyleAttr) {    super(context, attrs, defStyleAttr);    init();}
        private void init() { initTextView(); initEditText(); tvSetFocus(0);}/** * 輸入完成回調(diào)接口 */public interface OnVerificationCodeCompleteListener { void verificationCodeComplete(String verificationCode);}
        public void setOnVerificationCodeCompleteListener(OnVerificationCodeCompleteListener onVerificationCodeCompleteListener) { this.onVerificationCodeCompleteListener = onVerificationCodeCompleteListener;}

        7、用上自定義的參數(shù)

        到這運(yùn)行一下,基本可以顯示出來(lái),但是為了更靈活的使用嘛,我們之前寫(xiě)的attr就用上了。獲取參數(shù),初始化即可。
        <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) { //驗(yàn)證碼長(zhǎng)度 vCodeLength = typedArray.getInteger(attr, 6); } else if (attr == R.styleable.VerificationCodeView_vCodeTextColor) { //驗(yàn)證碼字體顏色 tvTextColor = typedArray.getColor(attr, Color.BLACK); } else if (attr == R.styleable.VerificationCodeView_vCodeTextSize) { //驗(yàn)證碼字體大小 tvTextSize = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 8, getResources().getDisplayMetrics())); } else if (attr == R.styleable.VerificationCodeView_vCodeWidth) { //方框?qū)挾?/span> tvWidth = typedArray.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics())); } else if (attr == R.styleable.VerificationCodeView_vCodeHeight) { //方框?qū)挾?/span> 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){ //默認(rèn)背景 tvBgNormal = typedArray.getResourceId(attr,R.drawable.verification_code_et_bg_normal); }else if(attr == R.styleable.VerificationCodeView_vCodeBackgroundFocus){ //焦點(diǎn)背景 tvBgFocus = typedArray.getResourceId(attr,R.drawable.verification_code_et_bg_focus); } } //用完回收 typedArray.recycle(); init();}

        源碼地址:
        https://github.com/Goodbao/VerificaitionCodeView
        到這里就結(jié)束啦。

        瀏覽 119
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            97人妻无码 | 掀开裙子从后面猛地挺进公交车里 | 男女草逼| 骚货熟妇| 女人18毛片水真多免费播放 | 男人手机天堂 | 操鼻免费素材网站 | 少妇高清精品毛片在线视频 | 中国色综合 | 欧美国产在线观看 |