Android custom verification code, password input box control implementation

Results the following

Dynamic figure

The basic idea

A horizontal LinearLayout, which contains a 1px EditText and n TextViews, listens to the Input characters of the EditText and sets the characters to the corresponding TextView.

Come on! Code on!!

VerifyEditText.java

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;

/** * Created by SongSenior on 2021/4/16 * EditText and n textViews */
public class VerifyEditText extends LinearLayout {
    // The default number of items is 4
    private final static int DEFAULT_ITEM_COUNT = 4;
    // The default width of each item is 100
    private final static int DEFAULT_ITEM_WIDTH = 100;
    // The default spacing for each item is 50
    private final static int DEFAULT_ITEM_MARGIN = 50;
    // The default font size for each item is 14
    private final static int DEFAULT_ITEM_TEXT_SIZE = 14;
    // by default, the password is displayed in plain text for 200ms and then in ciphertext
    private final static int DEFAULT_PASSWORD_VISIBLE_TIME = 200;

    private final List<TextView> mTextViewList = new ArrayList<>();
    private EditText mEditText;
    private Drawable drawableNormal, drawableSelected;
    private Context mContext;
    // Input completes listening
    private InputCompleteListener mInputCompleteListener;

    public VerifyEditText(Context context) {
        this(context, null);
    }

    public VerifyEditText(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VerifyEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, @Nullable AttributeSet attrs) {
        mContext = context;
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER);
        @SuppressLint("CustomViewStyleable") TypedArray obtainStyledAttributes =
                getContext().obtainStyledAttributes(attrs, R.styleable.verify_EditText);
        drawableNormal = obtainStyledAttributes.getDrawable(R.styleable.verify_EditText_verify_background_normal);
        drawableSelected = obtainStyledAttributes.getDrawable(R.styleable.verify_EditText_verify_background_selected);
        int textColor = obtainStyledAttributes.getColor(R.styleable.verify_EditText_verify_textColor,
                ContextCompat.getColor(context, android.R.color.black));
        int count = obtainStyledAttributes.getInt(R.styleable.verify_EditText_verify_count, DEFAULT_ITEM_COUNT);
        int inputType = obtainStyledAttributes.getInt(R.styleable.verify_EditText_verify_inputType, InputType.TYPE_CLASS_NUMBER);
        int passwordVisibleTime = obtainStyledAttributes.getInt(R.styleable.verify_EditText_verify_password_visible_time, DEFAULT_PASSWORD_VISIBLE_TIME);
        int width = (int) obtainStyledAttributes.getDimension(R.styleable.verify_EditText_verify_width, DEFAULT_ITEM_WIDTH);
        int height = (int) obtainStyledAttributes.getDimension(R.styleable.verify_EditText_verify_height, 0);
        int margin = (int) obtainStyledAttributes.getDimension(R.styleable.verify_EditText_verify_margin, DEFAULT_ITEM_MARGIN);
        float textSize = px2sp(context,obtainStyledAttributes.getDimension(R.styleable.verify_EditText_verify_textSize, sp2px(context,DEFAULT_ITEM_TEXT_SIZE)));
        boolean password = obtainStyledAttributes.getBoolean(R.styleable.verify_EditText_verify_password, false);
        obtainStyledAttributes.recycle();
        if (count < 2) count = 2;// At least 2 items

        mEditText = new EditText(context);
        mEditText.setInputType(inputType);
        mEditText.setLayoutParams(new LinearLayout.LayoutParams(1.1));
        mEditText.setCursorVisible(false);
        mEditText.setBackground(null);
        mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(count)});// Limit the input length to count
        mEditText.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) {
                TextView textView = mTextViewList.get(start);// Get the corresponding textView
                if (before == 0) {/ / input
                    CharSequence input = s.subSequence(start, s.length());// Get the newly entered word
                    textView.setText(input);
                    if (password) {// Ciphertext display is required
                        textView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        //passwordVisibleTime Set to ciphertext display after milliseconds
                        textView.postDelayed(() ->
                                        textView.setTransformationMethod(PasswordTransformationMethod.getInstance()),
                                passwordVisibleTime);
                    }
                    setTextViewBackground(textView, drawableSelected);
                } else {/ / delete
                    textView.setText("");
                    setTextViewBackground(textView, drawableNormal);
                }
                if(mInputCompleteListener ! =null && s.length() == mTextViewList.size())
                    mInputCompleteListener.complete(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {}}); addView(mEditText);// Click to bring up the soft keyboard
        setOnClickListener(v -> {
            mEditText.requestFocus();
            showSoftKeyBoard();
        });
        // Iterate to generate textView
        for (int i = 0; i < count; i++) {
            TextView textView = new TextView(context);
            textView.setTextSize(textSize);
            textView.setGravity(Gravity.CENTER);
            textView.setTextColor(textColor);
            LayoutParams layoutParams = new LayoutParams(width, height == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : height);
            if (i == 0)
                layoutParams.leftMargin = -1;
            elselayoutParams.leftMargin = margin; textView.setLayoutParams(layoutParams); setTextViewBackground(textView, drawableNormal); addView(textView); mTextViewList.add(textView); }}/** * When view is added to window, delay 500ms to pop up soft keyboard */
    @Override
    protected void onAttachedToWindow(a) {
        super.onAttachedToWindow();
        mEditText.postDelayed(this::showSoftKeyBoard, 500);
    }

    /** * Set the background *@param textView
     * @param drawable
     */
    private void setTextViewBackground(TextView textView, Drawable drawable) {
        if(drawable ! =null)
            textView.setBackground(drawable);
    }

    /** * gets the current input **@return* /
    public String getContent(a) {
        Editable text = mEditText.getText();
        if (TextUtils.isEmpty(text)) return "";
        return mEditText.getText().toString();
    }

    /** * clear the contents */
    public void clearContent(a) {
        mEditText.setText("");
        for (int i = 0; i < mTextViewList.size(); i++) {
            TextView textView = mTextViewList.get(i);
            textView.setText(""); setTextViewBackground(textView, drawableNormal); }}/** * Sets the default content **@param content
     */
    public void setDefaultContent(String content) {
        mEditText.setText(content);
        mEditText.requestFocus();
        char[] chars = content.toCharArray();
        int min = Math.min(chars.length, mTextViewList.size());
        for (int i = 0; i < min; i++) {
            char aChar = chars[i];
            String s = String.valueOf(aChar);
            TextView textView = mTextViewList.get(i);
            textView.setText(s);
            setTextViewBackground(textView, drawableSelected);
        }
        if(mInputCompleteListener ! =null && min == mTextViewList.size())
            mInputCompleteListener.complete(content.substring(0, min));

    }

    /** * displays a soft keyboard */
    private void showSoftKeyBoard(a) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.SHOW_FORCED);
    }

    /** * Add input completed listener **@param inputCompleteListener
     */
    public void addInputCompleteListener(InputCompleteListener inputCompleteListener) {
        mInputCompleteListener = inputCompleteListener;
        Editable content = mEditText.getText();
        if (!TextUtils.isEmpty(content) && content.toString().length() == mTextViewList.size()) {
            mInputCompleteListener.complete(content.toString());
        }
    }

    public interface InputCompleteListener {
        void complete(String content);
    }

    private int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5 f);
    }

    private int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;  
        return (int) (spValue * fontScale + 0.5 f); }}Copy the code

Attribute definitions

<resources xmlns:tools="http://schemas.android.com/tools">
    <declare-styleable name="verify_EditText">
        <! -- Number of verification codes -->
        <attr name="verify_count" format="integer"/>
        <! -- Width of TextView -->
        <attr name="verify_width" format="dimension"/>
        <! -- TextView height -->
        <attr name="verify_height" format="dimension"/>
        <! -- TextView spacing -->
        <attr name="verify_margin" format="dimension"/>
        <! -- TextView font size -->
        <attr name="verify_textSize" format="dimension"/>
        <! -- TextView font color -->
        <attr name="verify_textColor" format="color"/>
        <! -- TextView with no value background -->
        <attr name="verify_background_normal" format="reference"/>
        <! -- TextView has value background -->
        <attr name="verify_background_selected" format="reference"/>
        <! -- Whether to hide password -->
        <attr name="verify_password" format="boolean"/>
        <! Password display time ms-->
        <attr name="verify_password_visible_time" format="integer"/>
        <! -- editText input type -->
        <attr name="verify_inputType">
            <flag name="none" value="0x00000000" />
            <flag name="text" value="0x00000001" />
            <flag name="textCapCharacters" value="0x00001001" />
            <flag name="textCapWords" value="0x00002001" />
            <flag name="textCapSentences" value="0x00004001" />
            <flag name="textAutoCorrect" value="0x00008001" />
            <flag name="textAutoComplete" value="0x00010001" />
            <flag name="textMultiLine" value="0x00020001" />
            <flag name="textImeMultiLine" value="0x00040001" />
            <flag name="textNoSuggestions" value="0x00080001" />
            <flag name="textUri" value="0x00000011" />
            <flag name="textEmailAddress" value="0x00000021" />
            <flag name="textEmailSubject" value="0x00000031" />
            <flag name="textShortMessage" value="0x00000041" />
            <flag name="textLongMessage" value="0x00000051" />
            <flag name="textPersonName" value="0x00000061" />
            <flag name="textPostalAddress" value="0x00000071" />
            <flag name="textPassword" value="0x00000081" />
            <flag name="textVisiblePassword" value="0x00000091" />
            <flag name="textWebEditText" value="0x000000a1" />
            <flag name="textFilter" value="0x000000b1" />
            <flag name="textPhonetic" value="0x000000c1" />
            <flag name="textWebEmailAddress" value="0x000000d1" />
            <flag name="textWebPassword" value="0x000000e1" />
            <flag name="number" value="0x00000002" />
            <flag name="numberSigned" value="0x00001002" />
            <flag name="numberDecimal" value="0x00002002" />
            <flag name="numberPassword" value="0x00000012" />
            <flag name="phone" value="0x00000003" />
            <flag name="datetime" value="0x00000004" />
            <flag name="date" value="0x00000014" />
            <flag name="time" value="0x00000024" />
        </attr>
    </declare-styleable>
</resources>
Copy the code

Method of use

Custom attributes

App :verify_count = "5"// Number of verification code items app:verify_width = "50dp"// Height of a single item app:verify_height = "50DP "// Width of a single item App :verify_textSize = "15sp"//item font size app:verify_textColor = "# ff00DD "//item Verify_background_normal = "@drawable/shape_bottom_line_normal"// Empty background app:verify_background_selected = "@drawable/shape_bottom_line_selected"// Background after input value app:verify_password = "true"// Display ciphertext true, Display plaintext false app: verify_password_visibLE_time = "200"// Enter a value of 200ms to display ciphertext app:verify_inputType = "None "// Use the mode and EditText InputType asCopy the code

Layout file


      
<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:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.songsenior.verifyedittext.VerifyEditText
        android:id="@+id/vet1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:verify_count = "4"
        android:layout_marginTop="30dp"
        app:verify_inputType = "number"
        app:verify_password = "true"
        app:verify_width = "20dp"
        app:verify_height = "20dp"
        app:verify_password_visible_time = "500"
        app:verify_textSize = "14sp"
        app:verify_margin = "25dp"
        app:verify_background_normal = "@drawable/shape_verify_edittext_default_bg"/>

    <com.songsenior.verifyedittext.VerifyEditText
        android:id="@+id/vet2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        app:verify_count = "5"
        app:verify_inputType = "text"
        app:verify_textSize = "20sp"
        app:verify_height = "30dp"
        app:verify_margin = "15dp"
        app:verify_background_normal = "@drawable/shape_bottom_line_normal"
        app:verify_background_selected = "@drawable/shape_bottom_line_selected"/>

    <com.songsenior.verifyedittext.VerifyEditText
        android:id="@+id/vet3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        app:verify_count = "6"
        app:verify_inputType = "number"
        app:verify_textSize = "25sp"
        app:verify_margin = "15dp"
        app:verify_background_normal = "@drawable/shape_verify_edittext_default_bg2"/>

</LinearLayout>
Copy the code

drawable

shape_verify_edittext_default_bg.xml


      
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#A3A3A3"/>
    <corners android:radius="5dp"/>
</shape>
Copy the code

shape_bottom_line_normal.xml


      
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <! -- This is the line -->
    <item>
        <shape>
            <solid android:color="#A3A3A3" />
        </shape>
    </item>
    <item android:bottom="2dp">
        <shape>
            <solid android:color="#FFFFFFFF" />
        </shape>
    </item>
</layer-list>
Copy the code

shape_bottom_line_selected.xml


      
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <! -- This is the line -->
    <item>
        <shape>
            <solid android:color="#FF03DAC5" />
        </shape>
    </item>
    <item android:bottom="2dp">
        <shape>
            <solid android:color="#FFFFFFFF" />
        </shape>
    </item>
</layer-list>
Copy the code

shape_verify_edittext_default_bg2.xml


      
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke android:width="1dp" android:color="#A3A3A3"/>
    <corners android:radius="5dp"/>
</shape>
Copy the code

Project depend on

## add Maven to build. Gradle root

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

Add dependencies

dependencies {
	        implementation 'com. Making. SongSenior: VerifyEditText: 1.0'
	}
Copy the code

The last attacheddemo