Kotlin - Android编程之自定义数字键盘(原创)

作者:余哥Cse
语言:Kotlin
时间:2016-07-17
版本:转载或复制等请注明信息,作者QQ407158004

说明:有时候,我们需要使用数字键盘数组密码等内容,并且要求打乱其中的数字顺序,因此我们定义了如下数字键盘。
数字随机出现
按钮点击效果
点击字面返回事件

其他说明:
代码中的一些属性可转移至XML中做属性实现,暂不提供实现方式。
请自行优化代码及配置XML可用属性,此处暂不给出

Kotlin - Android编程之自定义数字键盘(原创)_第1张图片
18144857_oZB0.jpg
package com.boyou.autoservice.extend.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import java.util.*

/**
 * Created by Mrper on 16/07/17.
 * 虚拟键盘控件
 */
class KeyBoardView : View {

    companion object {
        const val KEY_INIT = 0
        const val KEY_DELETE = 10
        const val KEY_OK = 11
        const val COLUMN_MAX = 3
        const val ROW_MAX = 4
    }

    interface OnKeyPressListener {
        fun onKeyPress(key: String)
    }

    private var onKeyPressListener: OnKeyPressListener? = null
    private val _keys: Array> = Array(ROW_MAX, { Array(COLUMN_MAX, { KEY_INIT }) })
    private val _paint: Paint = Paint()
    private var _bw: Int = 0
    private var _bh: Int = 0
    private var _sx: Int = -1
    private var _sy: Int = -1

    private var _textSize: Int = 40
    private var _textColor: Int = Color.BLACK
    private var _normalBgColor: Int = Color.LTGRAY
    private var _pressBgColor: Int = Color.GRAY
    private var _btnSpacing: Int = 10

    constructor(context: Context?) : super(context) {
        init(context, null, 0)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs, 0)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context, attrs, defStyleAttr)
    }

    /**
     * 初始化函数
     * @param context 上下文对象
     * @param attrs 属性
     * @param defStyleAttr
     */
    private fun init(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) {
        var index = 0 //序号
        val _keyElements = createRandomArray()
        for (y in 0..ROW_MAX - 1) {
            for (x in 0..COLUMN_MAX - 1) {
                if (y == 2 && x == 2) {
                    _keys[y][x] = KEY_DELETE
                } else if (y == 3 && x == 2) {
                    _keys[y][x] = KEY_OK
                } else {
                    _keys[y][x] = _keyElements[index]
                    index += 1
                }
            }
        }
    }

    /** 创建随机排序的0-9个数字 **/
    private fun createRandomArray(): Array {
        val random = Random()
        val _keyElements: Array = arrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
        for (i in 0.._keyElements.size - 1) {
            val j = random.nextInt(10)
            val tmp = _keyElements[j]
            _keyElements[j] = _keyElements[i]
            _keyElements[i] = tmp
        }
        return _keyElements
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                _sx = event.x.toInt().div(_bw)
                _sy = event.y.toInt().div(_bh)
                invalidate()
                onKeyPressListener?.onKeyPress(_keys[_sy][_sx].toString())
                return true
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                _sx = -1
                _sy = -1
                invalidate()
                return true
            }
        }
        return super.onTouchEvent(event)
    }

    override fun draw(canvas: Canvas?) {
        super.draw(canvas)

        _paint.reset()
        _paint.isAntiAlias = true

        _bw = measuredWidth / 3
        _bh = measuredHeight / 4

        val spacing = 8f //间隔
        val rounds = 8f
        val rw = _bw - spacing * 2
        val rh = _bh - spacing * 2

        for (y in 0..3) {
            for (x in 0..2) {

                val pLeft = spacing * (2 * x + 1) + rw * x
                val pTop = spacing * (2 * y + 1) + rh * y
                val pRight = pLeft + rw
                val pBottom = pTop + rh

                _paint.style = Paint.Style.FILL
                _paint.color = if (_sx == x && _sy == y) Color.GRAY else Color.LTGRAY

                canvas?.drawRoundRect(RectF(pLeft, pTop, pRight, pBottom), rounds, rounds, _paint)

                _paint.style = Paint.Style.STROKE
                _paint.color = Color.BLACK
                _paint.textSize = 50f

                var text = _keys[y][x].toString()
                if (y == 2 && x == 2) {
                    text = "清除"
                } else if (y == 3 && x == 2) {
                    text = "确定"
                }
                val textWidth = _paint.measureText(text)
                val textHeight = _paint.fontMetrics.ascent + _paint.fontMetrics.descent
                canvas?.drawText(text, pLeft + (rw - textWidth) / 2, pTop + (rh - textHeight) / 2, _paint)
            }
        }

    }

}

你可能感兴趣的:(Kotlin - Android编程之自定义数字键盘(原创))