Android 自定义验证码Edittext输入框的实例代码(支持粘贴连续性)

转载地址:https://www.jb51.net/article/172229.htm

需求

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:

1

2

3

4

5

6

allprojects {

 repositories {

 ...

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

 }

}

Step 2. Add the dependency:

1

2

3

dependencies {

  implementation 'com.github.WShaobin:VerificationCodeInputView:1.0.2'

}

How to use

In layout

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

猜你喜欢

转载自blog.csdn.net/as425017946/article/details/116498652