在实际开发中,我们通常会遇到自定义键盘输入内容的情况,比如微信中的输入支付密码,验证码等场景,往往这些键盘都比较简单,通常是输入数字和小数点等内容,本篇文章将通过组合已有控件,打造一款通用的数字键盘 ⌨️
仓库地址:https://github.com/plain-dev/NumberKeyboardView
库清单
首先列觉一下本控件所用到的库
-
RecyclerView
数字键盘本体,承载键盘的按键的显示,响应输入等
-
BaseRecyclerViewAdapterHelper
一个强大的RecyclerView适配器库,封装常用逻辑,让适配器更加简洁
效果演示 ⌨️
实现过程
数字键盘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
然后初始化我们的RecyclerView
,做一些常规的配置,比如Adapter
、LayoutManager
等,然后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
Item的布局如下,一个显示文字,一个是删除键的图片,通过不同数据,来控制两者的显示和隐藏,比较简单粗暴
接下来就是RecyclerView
的数据了,我们这里的按键有0-9
、小数点
和删除
,直接一个List
集合就好
private fun initKeyValueList() {
if (null == keyValueList) {
keyValueList = ArrayList()
for (i in 1..12) {
val map = HashMap()
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
通过KeyboardHelper
帮助类,完成系统键盘的屏蔽以及EditText
和NumberKeyboardView
的绑定
helper.banSystemKeyboard(activity, editText)
helper.bind(editText, numberKeyboard, object : OnKeyboardChangeListener {
override fun onTextChange(text: String) {
inputContent = text
}
})
总结
通过上面的流程,可以感受到,开发一个简单的数字键盘还是很轻松的,借助自带的RecyclerView
就可以轻松完成 ❤️
项目已提交Github,欢迎点我进入仓库查看
最后感谢大家的观看
done