自定義密碼輸入框View

先看看效果圖~是不是你的菜
1661942722043.jpg

文字的字體顏色、大小、樣式直接設(shè)置textview的屬性就行。較好的就是加入個當前輸入的位置的變色。不過我們需求沒這個就沒加上了。想更多支持的就自己添加~這里我的需求就加了這點。
代碼:

class EditPassWordView(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {
    //背景畫筆
    private val mPaintBg = Paint(Paint.ANTI_ALIAS_FLAG)

    //文字畫筆
    private val mPaintTv = TextPaint(Paint.ANTI_ALIAS_FLAG)

    //密碼位數(shù)
    private var passwordLength = 4

    //間隔  ->   dp2px
    private var itemSpace = 5

    //單個數(shù)字包括背景寬度 dp2px
    private var itemWidth = 30

    //item背景顏色
    private var itemBackgroundColor = 0

    //item圓角大小
    private var itemRound = 5f

    //是否加密顯示
    private var isCipherEnable = false

    //加密顯示的文字
    private var cipherString = "*"

    //用于存儲輸入后的密碼
    private val password = arrayOfNulls<String>(passwordLength)

    //當前輸入位數(shù)
    private var currentInputPosition = 0

    //軟鍵盤管理器
    private var inputManager: InputMethodManager? =
        context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?

    //鍵盤監(jiān)聽
    private var keyListener = OnKeyListener { _, keyCode, event ->
        val action = event.action
        if (action == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                //刪除
                if (currentInputPosition == 0) {
                    return@OnKeyListener true
                }
                password[currentInputPosition - 1] = null
                currentInputPosition--
                postInvalidate()
                operationListener?.deleteOperationCallBack()
                return@OnKeyListener true
            }
            if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
                //數(shù)字鍵
                inputPassWord((keyCode - 7).toString())
                return@OnKeyListener true
            }
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                //確認鍵
                return@OnKeyListener true
            }
        }

        return@OnKeyListener false
    }

    init {
        val attributes = context.obtainStyledAttributes(attrs, R.styleable.EditPassWordView)
        itemBackgroundColor =
            attributes.getColor(R.styleable.EditPassWordView_itemBackgroundColor, Color.WHITE)
        itemRound = attributes.getDimension(R.styleable.EditPassWordView_itemRound, 5f)
        itemSpace = attributes.getDimension(R.styleable.EditPassWordView_itemSpace, 5f).toInt()
        isCipherEnable = attributes.getBoolean(R.styleable.EditPassWordView_isCipherEnable, false)
        passwordLength = attributes.getInt(R.styleable.EditPassWordView_passwordLength, 4)
        attributes.recycle()

        isFocusableInTouchMode = true

        mPaintBg.color = itemBackgroundColor

        mPaintTv.textSize = textSize
        mPaintTv.color = textColors.defaultColor
        mPaintTv.typeface = typeface


        setOnKeyListener(keyListener)
        //數(shù)字鍵盤得用這個監(jiān)聽
        doOnTextChanged { text, start, _, _ ->
            val inputNumber = text.toString()
            val newNumber = inputNumber.substring(start, inputNumber.length)
            inputPassWord(newNumber)
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var width = 0
        when (MeasureSpec.getMode(widthMeasureSpec)) {
            MeasureSpec.UNSPECIFIED, MeasureSpec.AT_MOST -> {
                width = itemWidth * passwordLength + itemSpace * (passwordLength - 1)
            }

            MeasureSpec.EXACTLY -> {
                width = MeasureSpec.getSize(widthMeasureSpec)
                itemWidth = (width - itemSpace * (passwordLength - 1)) / passwordLength
            }
        }
        setMeasuredDimension(width, itemWidth)
    }

    override fun onDraw(canvas: Canvas) {
        drawBgItems(canvas)
        drawPasswordNumber(canvas)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_DOWN) {
            //獲取焦點
            requestFocus()
            inputManager?.showSoftInput(this, InputMethodManager.SHOW_FORCED)
            return true
        }
        return super.onTouchEvent(event)
    }

    //繪制背景
    private fun drawBgItems(canvas: Canvas) {
        for (i in password.indices) {
            //注意padding的影響
            val rect = RectF(
                (i * itemWidth + (i) * itemSpace + paddingStart).toFloat(),
                0f + paddingTop,
                ((i + 1) * itemWidth + i * itemSpace + paddingEnd).toFloat(),
                (itemWidth + paddingBottom).toFloat()
            )

            canvas.drawRoundRect(rect, itemRound, itemRound, mPaintBg)
        }
    }

    private lateinit var rectTv: Rect

    //繪制文字
    private fun drawPasswordNumber(canvas: Canvas) {
        for (i in password.indices) {
            if (password[i] != null) {
                //沒有開啟明文顯示,繪制密碼密文
                val txt = if (isCipherEnable) cipherString else password[i]
                //計算文字的寬度
                rectTv = Rect(
                    (i * itemWidth + (i) * itemSpace + paddingStart),
                    0 + paddingTop,
                    ((i + 1) * itemWidth + i * itemSpace + paddingEnd),
                    itemWidth + paddingBottom
                )
                mPaintTv.getTextBounds(txt.toString(), 0, txt!!.length, rectTv)
                val offset = (rectTv.top + rectTv.bottom) / 2
                canvas.drawText(
                    password[i]!!,
                    (paddingLeft + itemWidth * i + itemSpace * i + (itemWidth - rectTv.width()) / 2).toFloat(),
                    (paddingTop + itemWidth / 2).toFloat() - offset, mPaintTv
                )
            }
        }
    }


    private fun inputPassWord(number: String) {
        //加入判斷 currentInputPosition
        if (currentInputPosition == passwordLength) {
            return
        }
        password[currentInputPosition] = number
        currentInputPosition++
        postInvalidate()
        //判斷是否輸入完成還是輸入中
        if (currentInputPosition == passwordLength) {
            operationListener?.completeOperationCallBack(getTextContent())
        } else {
            operationListener?.inputOperationCallBack()
        }
    }

    //獲取輸入內(nèi)容
    fun getTextContent(): String {
        val sb = StringBuilder()
        for (p in password) {
            p?.let {
                sb.append(p)
            }
        }
        return sb.toString()
    }

    fun reset() {
        for (i in 0 until passwordLength) {
            password[i] = null
        }
        currentInputPosition = 0
        postInvalidate()
    }

    private var operationListener: OperationListener? = null

    fun setOperationListener(operationListener: OperationListener) {
        this.operationListener = operationListener
    }

    interface OperationListener {
        fun inputOperationCallBack()

        fun completeOperationCallBack(password: String)

        fun deleteOperationCallBack()
    }
}

自定義的styleable

    <declare-styleable name="EditPassWordView">
        <attr name="itemBackgroundColor" format="color" />
        <attr name="itemRound" format="dimension" />
        <attr name="itemSpace" format="dimension" />
        <attr name="isCipherEnable" format="boolean" />
        <attr name="passwordLength" format="integer" />
    </declare-styleable>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容