android自定义键盘
开始
最近开发密码锁功能,就是打开应用的时候需要输入密码才能进入应用的功能。于是就需要自定义一个数字键盘,给用户输入密码。这种键盘就不适合用系统的输入法键盘了,毕竟样式也不协调,键盘的内容也不可控。
KeyboardView
开始我是用最傻的办法一个个按钮布局成这样一个键盘,后来发现原来Android本来就提供了自定义键盘的方式。而且还蛮简单的。。。。。
首先定义一个键盘键位文件,就是定义键盘上面各个按键的位置的文件:number_keyboard.xml:
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:horizontalGap="3dp"
android:keyHeight="7.5%p"
android:keyWidth="33.33%p"
android:verticalGap="3dp"
>
<Row >
<Key
android:codes="49"
android:keyLabel="1" />
<Key
android:codes="50"
android:keyLabel="2" />
<Key
android:codes="51"
android:keyLabel="3" />
</Row>
<Row >
<Key
android:codes="52"
android:keyLabel="4" />
<Key
android:codes="53"
android:keyLabel="5" />
<Key
android:codes="54"
android:keyLabel="6" />
</Row>
<Row >
<Key
android:codes="55"
android:keyLabel="7" />
<Key
android:codes="56"
android:keyLabel="8" />
<Key
android:codes="57"
android:keyLabel="9" />
</Row>
<Row >
<Key
android:keyWidth="66.66%p"
android:codes="48"
android:keyLabel="0" />
<Key
android:codes="-5"
android:isRepeatable="true"
android:keyIcon="@mipmap/icon_backspace_666" />
</Row>
</Keyboard>
这个xml文件需要放在资源目录的xml目录下。
属性:
android:horizontalGap 每个键之间的横向的空隙
android:verticalGap 每个键之间的纵向的空隙
android:keyWidth 每个键的宽度
android:keyHeight 每个键的高度
android:keyIcon 键可以显示图片
android:keyLabel 键可以显示文字
android:codes 键的值
这些属性的值可以是普通的dimensions,也可以用百分比,30%p就代表parent的30%
定好了这个Keyboard的xml后,还需要在布局页面中定义一个键盘布局的view
<android.inputmethodservice.KeyboardView
android:id="@+id/keyboardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/background"
android:keyBackground="@drawable/ripple_background_normal"
android:focusable="true"
android:focusableInTouchMode="true"
android:keyTextColor="@color/secondary_text"
android:keyTextSize="24sp"
android:labelTextSize="18sp"
android:shadowColor="#FFFFFF"
android:shadowRadius="0.0"
/>
这个就是最终在手机页面上显示的view,他的属性:
android:background 整个键盘的背景
android:keyBackground 这个每个键的背景
android:keyTextColor 这个每个键上的文字的颜色
android:keyTextSize 每个键上文字的大小
上面定义的键的xml如何和这个KeyboardView结合起来呢。
private val keyboardNumber: Keyboard by lazy { Keyboard(this, R.xml.number_keyboard) }
有了Keyboard对象后给View设置该对象
keyboardview.keyboard = keyboardNumber
在给keyboardview添加一个按键的监听(KeyboardView.OnKeyboardActionListener):
keyboardview_lock.setOnKeyboardActionListener(object : KeyboardView.OnKeyboardActionListener {
override fun onPress(primaryCode: Int) {
//键盘按下的时候
}
override fun onRelease(primaryCode: Int) {
//键盘释放的时候
}
override fun onKey(primaryCode: Int, keyCodes: IntArray?) {
//点击了某一个键
}
override fun onText(text: CharSequence?) {
}
//下面几个是在键盘上面滑动的监听
override fun swipeRight() {
}
override fun swipeLeft() {
}
override fun swipeUp() {
}
override fun swipeDown() {
}
})
这个过程还是相当简单的。
The End !