转载请注明出处:http://blog.youkuaiyun.com/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