自定义View练习 - 汉字键盘
练习来源
最终效果图
基本知识
以下内容摘自上面的文章
一、软键盘介绍
实现软键盘主要用到了系统的两个类:Keyboard和KeyboardView。
Keyboard类源码的介绍是: Listener for virtual keyboard events.即用于监听虚拟键盘。
KeyboardView类源码的介绍是: A view that renders a virtual {@link Keyboard}. It handles rendering of keys and detecting key presses and touch movements.即它处理绘制键盘和检测按键和触摸动作。
它里面有很多方法,在我们自定义的软键盘很多属性,就需要我们用这个类来设置。比如:
keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
keyboardView.setKeyboard(k);
keyboardView.setEnabled(true);
keyboardView.setPreviewEnabled(true);
keyboardView.setVisibility(View.VISIBLE);
keyboardView.setOnKeyboardActionListener(listener);
了解一些源码,就可以是我们知道我们为什么要这样写,为什么要这样做了!
二、数字软键盘的布局
首先在res下新建xml文件夹,在xml文件夹中新建symbols.xml文件,这个布局文件主要是实现数字软键盘的布局,每一个按键都有一个codes值,在类中就是通过codes值来监听每一个按钮。
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="20%p" android:horizontalGap="0px"
android:verticalGap="0px" android:keyHeight="@dimen/key_height">
<Row>
<Key android:codes="49" android:keyLabel="1" />
<Key android:codes="50" android:keyLabel="2" />
<Key android:codes="51" android:keyLabel="3" />
<Key android:codes="52" android:keyLabel="4" />
<Key android:codes="-5" android:keyIcon="@drawable/sym_keyboard_delete" />
</Row>
<Row>
<Key android:codes="53" android:keyLabel="5" />
<Key android:codes="54" android:keyLabel="6" />
<Key android:codes="55" android:keyLabel="7" />
<Key android:codes="56" android:keyLabel="8" />
<Key android:codes="-2" android:keyLabel="中文" />
</Row>
<Row>
<Key android:codes="57" android:keyLabel&