Android自定义View之数字键盘 (NumberKeyboardView)

在实际开发中,我们通常会遇到自定义键盘输入内容的情况,比如微信中的输入支付密码,验证码等场景,往往这些键盘都比较简单,通常是输入数字和小数点等内容,本篇文章将通过组合已有控件,打造一款通用的数字键盘 ⌨️

仓库地址:https://github.com/plain-dev/NumberKeyboardView

库清单🧾

首先列觉一下本控件所用到的库

  • RecyclerView

    数字键盘本体,承载键盘的按键的显示,响应输入等

  • BaseRecyclerViewAdapterHelper

    一个强大的RecyclerView适配器库,封装常用逻辑,让适配器更加简洁

效果演示 ⌨️

DEMO

实现过程

数字键盘View

一开始想起来做数字键盘的时候,第一个想到的是GridLayout,然后想到了GridView,前者可以很好的实现这种需求,但扩展性不高,后者做这种网格布局是再适合不过了,但现在有了RecyclerView则不需要GridView了,因为RecyclerView通过指定布局管理器,可以实现多种布局效果,这里我们就用到了GridLayoutMananger

这里我们继承RelativeLayout来承载此View,里面则是一个RecyclerView

class NumberKeyboardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
    
    ......
    
}

布局也非常简单,仅一个RecyclerView

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rvKeyboard"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fbfbfb" />

然后初始化我们的RecyclerView,做一些常规的配置,比如AdapterLayoutManager等,然后UI上Item之间还有线段分割,这里用到了自定义ItemDecoration,这是RecyclerView非常方便的一个特性,可以自定义Item的装饰器。

private fun initRv(context: Context) {
    adapter = NumberKeyboardAdapter(keyValueList)
    rvKeyboard.layoutManager = GridLayoutManager(context, 3)
    val dividerItemDecoration = GridDividerItemDecoration.Builder(context)
            .setShowLastLine(false)
            .setHorizontalSpan(R.dimen.SIZE_1)
            .setVerticalSpan(R.dimen.SIZE_1)
            .setColor(Color.parseColor("#ebebeb"))
            .build()
    rvKeyboard.addItemDecoration(dividerItemDecoration)
    rvKeyboard.adapter = adapter
}

适配器这里用到了第三方库BaseRecyclerViewAdapterHelper,结构很清晰

class NumberKeyboardAdapter internal constructor(data: List<Map<String, String>>?) :

    BaseQuickAdapter<Map<String, String>, BaseViewHolder>(R.layout.item_number_keyboard, data) {

    override fun convert(viewHolder: BaseViewHolder, item: Map<String, String>) {
        val tvKey = viewHolder.getView<TextView>(R.id.tvKey)
        val rlDel = viewHolder.getView<RelativeLayout>(R.id.rlDel)
        val position = viewHolder.layoutPosition
        if (position == Constant.KEYBOARD_DEL) {
            rlDel.visibility = View.VISIBLE
            tvKey.visibility = View.INVISIBLE
        } else {
            rlDel.visibility = View.INVISIBLE
            tvKey.visibility = View.VISIBLE
            tvKey.text = item[Constant.MAP_KEY_NAME]
        }
    }

}

Item的布局如下,一个显示文字,一个是删除键的图片,通过不同数据,来控制两者的显示和隐藏,比较简单粗暴

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fbfbfb">

    <TextView
        android:id="@+id/tvKey"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textStyle="bold"
        android:includeFontPadding="false"
        android:textColor="#333333"
        android:textSize="26sp" />

    <RelativeLayout
        android:id="@+id/rlDel"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_centerInParent="true">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@drawable/icon_keyboard_del" />

    </RelativeLayout>

</RelativeLayout>

接下来就是RecyclerView的数据了,我们这里的按键有0-9小数点删除,直接一个List集合就好

private fun initKeyValueList() {
    if (null == keyValueList) {
        keyValueList = ArrayList()
        for (i in 1..12) {
            val map = HashMap<String, String>()
            when {
                i < Constant.KEYBOARD_ZERO -> map[Constant.MAP_KEY_NAME] = i.toString()
                i == Constant.KEYBOARD_ZERO -> map[Constant.MAP_KEY_NAME] = "."
                i == Constant.KEYBOARD_DEL -> map[Constant.MAP_KEY_NAME] = 0.toString()
                else -> map[Constant.MAP_KEY_NAME] = ""
            }
            keyValueList!!.add(map)
        }
    }
}

这样,键盘部分就差不多了,然后将此View添加到容器中就好了

val view = LayoutInflater.from(context).inflate(R.layout.layout_number_keyboard, this, false)
addView(view)

数字键盘帮助类

以上我们的键盘就可以正常显示了,但还没有真正的点击操作。这里我们封装一个键盘帮助类KeyboardHelper,在这里实现键盘的操作,并封装一些常用的方法

这里我们将本类设计为单例模式

companion object {

    @Volatile
    private var instance: KeyboardHelper? = null
        get() {
            if (field == null) {
                field = KeyboardHelper()
            }
            return field
        }

    @Synchronized
    fun get(): KeyboardHelper {
        return instance!!
    }
}

我们要想使用自定义的键盘,首先就要屏蔽掉系统键盘,一般常用的方法就是通过反射,这里封装一个方法,暴露给外部使用

@SuppressLint("ObsoleteSdkInt")
fun banSystemKeyboard(context: Activity, editText: EditText) {
    if (android.os.Build.VERSION.SDK_INT <= 10) {
        editText.inputType = InputType.TYPE_NULL
    } else {
        context.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        try {
            val cls = EditText::class.java
            val setShowSoftInputOnFocus: Method
            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", Boolean::class.javaPrimitiveType!!)
            setShowSoftInputOnFocus.isAccessible = true
            setShowSoftInputOnFocus.invoke(editText, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

既然是键盘,那它的使用方肯定是输入框EditText,这里我们给外部暴露一个bind方法,绑定两者,并提供一个接口,回调输入的内容给外部

fun bind(
    editText: EditText,
    numberKeyboardView: NumberKeyboardView,
    listener: OnKeyboardChangeListener
) {
    editText.requestFocus()
    editText.isSaveEnabled = false
    valueList = numberKeyboardView.getKeyValueList()
    val adapter = numberKeyboardView.adapter
    if (null != adapter && !(null == valueList || valueList!!.isEmpty())) {
        processKeyClick(editText, adapter)
        observedEditText(editText, listener)
    }
}

可以看到,方法里面主要调用了两个方法,processKeyClick是用来处理键盘点击的,observedEditText是用来观察EditText的,如果输入内容发生变化,则会通知外部刷新

首先看processKeyClick,这里就是为adapter设置点击事件监听,BaseRecyclerViewAdapterHelper为我们提供了很好的方法,直接调用即可

adapter.onItemClickListener =
        BaseQuickAdapter.OnItemClickListener { 
        _,
        _,
        position ->
        respondKeyClick(editText, position)
}

接下来就是对每一个键的处理,代码虽然长,但很好理解,主要就是拼接字符串、首位0和小数点的判断,如果光标不在末尾,则用到了插入删除方法,进行处理

private fun respondKeyClick(et: EditText, pos: Int) {
    if (pos < 11 && pos != 9) { // click number 0 - 9
        var amount = et.text.toString().trim { it <= ' ' }
        amount += valueList!![pos][Constant.MAP_KEY_NAME]
        val index = et.selectionStart
        // cannot enter zero in the first place
        if (pos == 10 && index == 0) {
            return
        }
        if (index == amount.length - 1) {
            et.setText(amount)
            val ea = et.text
            et.setSelection(ea.length)
        } else {
            val editable = et.text
            editable.insert(index, valueList!![pos][Constant.MAP_KEY_NAME])
        }
    } else {
        if (pos == 9) { // click dot
            var amount = et.text.toString().trim { it <= ' ' }
            if (TextUtils.isEmpty(amount)) {
                return
            }
            val index = et.selectionStart
            if (index == amount.length && !amount.contains(".")) {
                amount += valueList!![pos][Constant.MAP_KEY_NAME]!!
                et.setText(amount)
                val ea = et.text
                et.setSelection(ea.length)
            } else if (index > 0 && !amount.contains(".")) {
                val editable = et.text
                editable.insert(index, valueList!![pos][Constant.MAP_KEY_NAME])
            }
        }
        if (pos == 11) { // click delete
            var amount = et.text.toString().trim { it <= ' ' }
            if (amount.isNotEmpty()) {
                val index = et.selectionStart
                if (index == amount.length) {
                    amount = amount.substring(0, amount.length - 1)
                    et.setText(amount)
                    val ea = et.text
                    et.setSelection(ea.length)
                } else {
                    if (index != 0) {
                        val editable = et.text
                        editable.delete(index - 1, index)
                    }
                }
            }
        }
    }
}

然后就是对输入内容的回调,这里用到了TextWatcher类,通过它就可以观察EditText输入框内容的变化

private fun observedEditText(editText: EditText, listener: OnKeyboardChangeListener) {
    if (null == watcher) {
        watcher = object : TextWatcher {

            override fun beforeTextChanged(
                s: CharSequence,
                start: Int,
                count: Int,
                after: Int
            ) {
                    //Empty
            }

            override fun onTextChanged(
                s: CharSequence, 
                start: Int, 
                before: Int, 
                count: Int
            ) {
                    //Empty
            }

            override fun afterTextChanged(s: Editable) {
                val inputVal = editText.text.toString()
                val effectiveVal = perfectDecimal(inputVal, 3, 2)
                if (effectiveVal != inputVal) {
                    editText.setText(effectiveVal)
                    val pos = editText.text.length
                    editText.setSelection(pos)
                }
                callBackInputResult(listener, effectiveVal)
            }

        }
    }
    editText.addTextChangedListener(watcher)
}

这里我们对输入的内容做一下限制,小数点前最多输入3位,小数点后最多输入2位

private fun perfectDecimal(inputVal: String, maxBeforeDot: Int, maxDecimal: Int): String {
    var inputVal = inputVal
    if (inputVal.isEmpty()) return ""
    if (inputVal[0] == '.') inputVal = "0$inputVal"
    val max = inputVal.length
    val rFinal = StringBuilder()
    var after = false
    var i = 0
    var up = 0
    var decimal = 0
    var t: Char
    while (i < max) {
        t = inputVal[I]
        if (t != '.' && !after) {
            up++
            if (up > maxBeforeDot) return rFinal.toString()
        } else if (t == '.') {
            after = true
        } else {
            decimal++
            if (decimal > maxDecimal) return rFinal.toString()
        }
        rFinal.append(t)
        I++
    }
    return rFinal.toString()
}

这样我们只需回调合法的输入内容就可以了,然后对回调的内容也做一下限制,如果两次输入内容一致,就不回调了,通过lastCallbackResult来记录一下

private fun callBackInputResult(listener: OnKeyboardChangeListener?, str: String) {
    if (null != listener) {
        if (str != lastCallbackResult) {
            lastCallbackResult = str
            listener.onTextChange(str)
        }
    }
}

使用方法

通过上面的封装,我们的数字键盘就算完工了,而且使用起来也很方便

使用数字键盘View

<top.i97.numberkeyboard.view.NumberKeyboardView
        android:id="@+id/numberKeyboard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fbfbfb" />

通过KeyboardHelper帮助类,完成系统键盘的屏蔽以及EditTextNumberKeyboardView的绑定

helper.banSystemKeyboard(activity, editText)
helper.bind(editText, numberKeyboard, object : OnKeyboardChangeListener {
    override fun onTextChange(text: String) {
        inputContent = text
    }
})

总结

通过上面的流程,可以感受到,开发一个简单的数字键盘还是很轻松的,借助自带的RecyclerView就可以轻松完成 ❤️

项目已提交Github,欢迎点我进入仓库查看

最后感谢大家的观看

done

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容