1. 程式人生 > 程式設計 >Android 自定義驗證碼輸入框的例項程式碼(支援貼上連續性)

Android 自定義驗證碼輸入框的例項程式碼(支援貼上連續性)

需求

1、能自定義輸入框個數和樣式

2、支援長按貼上或剪下板內容自動填充(貼上連續性)

其中第2點是最為重要的,正是其他人沒有這點,逼得自己弄一個

示例

別人的示例:

在這裡插入圖片描述

貼上居然不支援連續性,只能貼上第一個字元,所以用的有點難受

自己的示例:

在這裡插入圖片描述

原理

大致是Edittext + n* TextView,然後設定edittext字型跟背景顏色都為透明,隱藏游標

Edittext:監聽edittext每次輸入一個字元就賦值到對應的TextView上,然後在清空自己

下劃線:在TextView下面新增View

游標:這裡的每個TextView的焦點游標其實對View設定了ValueAnimator

貼上:貼上彈窗是自定義的PopupWindow

原始碼有詳細註釋,這裡就不一一說明

Github

https://github.com/WShaobin/VerificationCodeInputView

Gradle

Step 1. Add it in your root build.gradle at the end of repositories:

allprojects {
 repositories {
 ...
 maven { url 'https://jitpack.io' }
 }
}

Step 2. Add the dependency:

dependencies {
  implementation 'com.github.WShaobin:VerificationCodeInputView:1.0.2'
}

How to use

In layout

<com.wynsbin.vciv.VerificationCodeInputView
  android:id="@+id/vciv_code"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="48dp"
  android:gravity="center"
  android:orientation="horizontal"
  app:vciv_et_background="@android:color/white"
  app:vciv_et_foucs_background="@android:color/holo_orange_dark"
  app:vciv_et_cursor_color="@color/colorPrimary"
  app:vciv_et_height="58dp"
  app:vciv_et_inputType="number"
  app:vciv_et_number="6"
  app:vciv_et_text_color="@android:color/black"
  app:vciv_et_text_size="18sp"
  app:vciv_et_underline_default_color="@android:color/holo_green_dark"
  app:vciv_et_underline_focus_color="@android:color/holo_blue_bright"
  app:vciv_et_underline_height="2dp"
  app:vciv_et_underline_show="true"
  app:vciv_et_width="58dp" />

In Java Code

VerificationCodeInputView view = findViewById(R.id.vciv_code);
view.setOnInputListener(new VerificationCodeInputView.OnInputListener() {
  @Override
  public void onComplete(String code) {
    Toast.makeText(MainActivity.this,code,Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onInput() {

  }
});

//清除驗證碼
view.clearCode();

Attributes

VCInputType

輸入框背景色支援型別

1、@drawable/xxx

2、@color/xxx

3、#xxxxxx

總結

以上所述是小編給大家介紹的Android 自定義驗證碼輸入框的例項程式碼(支援貼上連續性),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!