kotlin实现的简单个人账户管理APP(三) 自定义View仿支付宝的密码输入框/密码相关逻辑

转载请注明出处:http://blog.csdn.net/a512337862/article/details/78874322

前言

1.本篇博客相关的项目介绍请参考基于kotlin实现的简单个人账户管理APP
2.本篇博客是介绍利用kotlin 自定义View实现仿支付宝密码输入框以及密码输入相关逻辑。
3.因为本人是kotlin初学者,博客如果有任何问题请指出。

截图效果

这里写图片描述

代码分析

仿支付宝密码输入框

InputPswView

代码如下:

/**
 * Author : BlackHao
 * Time : 2017/12/7 14:36
 * Description : 自定义密码输入框
 */

class InputPswView(context: Context?, attrs: AttributeSet?) : EditText(context, attrs), TextWatcher {

    //边框颜色
    private var strokeColor: Int = Color.GRAY
    //圆角
    private var roundRadius: Int = 10
    //边框宽度
    private var strokeWidth = 4
    //画笔
    private var paint: Paint
    //密码字符数
    private var pswCount = 6
    //边框rect
    private var rectF: RectF
    private var roundRectF: RectF
    //Path用于圆角绘制边框
    private var roundPath: Path
    //输入完成监听
    lateinit var listener: InputListener

    init {
        val a = context?.obtainStyledAttributes(attrs, R.styleable.InputPswView, 0, 0)
        val n = a?.indexCount
        (0 until n!!).map { a.getIndex(it) }.forEach {
            when (it) {
                R.styleable.InputPswView_strokeColor -> strokeColor = a.getColor(it, Color.GRAY)
                R.styleable.InputPswView_roundRadius -> roundRadius = a.getDimension(it, TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_SP, 5f, resources.displayMetrics)).toInt()
                R.styleable.InputPswView_pswCount -> pswCount = a.getInt(it, 6)
                R.styleable.InputPswView_strokeWidth -> strokeWidth = a.getDimension(it, TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_SP, 10f, resources.displayMetrics)).toInt()
            }
        }
        //recycle
        a.recycle()
        //初始化画笔
        paint = Paint()
        paint.isAntiAlias = true
        paint.strokeWidth = strokeWidth.toFloat()
        paint.style = Paint.Style.STROKE

        rectF = RectF()
        roundRectF = RectF()
        roundPath = Path()

        //隐藏光标
        isCursorVisible = false
        //取消下划线
        background = ColorDrawable(Color.TRANSPARENT)
        //设置输入监听
        addTextChangedListener(this)
        //设置最大长度
        filters = arrayOf(InputFilter.LengthFilter(pswCount))
    }

    override fun onDraw(canvas: Canvas?) {
//        super.onDraw(canvas)
        //通过密码数获取输入框宽度
        val boxWidth = (width / pswCount).toFloat()
        //设置画笔为stroke
        paint.style = Paint.Style.STROKE
        //设置颜色为strokeColor
        paint.color = strokeColor
        //判断roundRadius,必须小于width / 2 以及 height / 2
        if (roundRadius > width / 2 || roundRadius > height / 2) {
            roundRadius = if (width > height) height / 2 else width / 2
        }
        //这里stroke是为了让边框能完全显示,如果rectF
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值