2018-03-20 Android自定义键盘的简单实现

概述

转载:http://blog.csdn.net/tianzhaoai/article/details/64130332
突然发现好多软件都使用了自己定义的软键盘。自己就想着先把这块坑先踩踩把,以后掉坑的时候不至于摔的太惨。言归正传,对于自定义软键盘。需要用到系统提供的两个类:Keyboard和KeyboardView。

Keyboard

设计键盘的布局文件,官方上对Keyboard是这么解释的

Loads an XML description of a keyboard and stores the attributes of the keys. 
A keyboard consists of rows of keys.The layout file for a keyboard contains XML that looks like the following snippet:

也就是说这个Keyboard是一个xml文件,可以用来进行键盘的布局,格式如下:

<Keyboard
         android:keyWidth="%10p"
         android:keyHeight="50px"
         android:horizontalGap="2px"
         android:verticalGap="2px" >
     <Row android:keyWidth="32px" >
         <Key
            android:codes="44"
            android:keyLabel=","
            android:horizontalGap="6dp"
            android:keyWidth="8.33334444%p"/>
         ...
     </Row>
     ...
 </Keyboard>

下面是Keyboard描述键盘时的一些常用属性介绍

属性 描述
codes 按键对应的输出值,可以为unicode值或则逗号(,)分割的多个值,也可以为一个字 符串。在字符串中通过“\”来转义特殊字符,例如 ‘\n’ 或则 ‘\uxxxx’ 。Codes通常用来定义该键的键码,例如上图中的数字按键1对应的为49;如果提供的是逗号分割的多个值则和普通手机输入键盘一样在多个值之间切换
keyLabel 按键显示的文本内容
keyIcon 按键显示的图标内容,如果指定了该值则在显示的时候显示为图片不显示文本
keyWidth 按键的宽度,可以为精确值或则相对值,对于精确值支持多种单位,例如:像素,英寸 等;相对值为相对于基础取值的百分比,为以% 或则%p 结尾,其中%p表示相对于父容器
keyHeight 按键的高度,取值同keyWidth
horizontalGap 按键前的间隙(水平方向),取值取值同keyWidth
isSticky 按键是否为sticky的。例如Shift大小写切换按键,具有两种状态,按下状态和正常状态,取值为true或则false
isModifier 按键是否为功能键( modifier key ) ,例如 Alt 或则 Shift 。取值为true或则false
keyOutputText 按键输出的文本内容,取值为字符串
isRepeatable 按键是否是可重复的,如果长按该键可以触发重复按键事件则为true,否则为false
keyEdgeFlags 按键的对齐指令,取值为left或则right

KeyboardView

处理绘制,检测按键,触摸动作等

A view that renders a virtual Keyboard. It handles rendering of keys and detecting key presses and touch movements.

在这里渲染虚拟键盘的视图,并且处理按键的触摸和移动等操作。在Activity的布局文件中可以这样定义

<android.inputmethodservice.KeyboardView
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="@color/gray"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:keyBackground="@drawable/bg_keyboard_selector"
    android:keyPreviewLayout="@layout/key_preview_layout"
    android:keyTextColor="@color/keyTextColor"
    android:visibility="gone"
    />

下面介绍一些KeyboardView的属性

属性 描述
android:keyBackground 键的背景图
android:keyPreviewLayout 击键盘上的某个键时,短暂弹出的提示布局文件
android:keyPreviewOffset 击键盘上的某个键时,短暂弹出布局的垂直偏移量
android:keyTextColor 按键中的keyLabel的颜色
android:keyTextSize 按键中的keyLabel的大小
android:labelTextSize 如果有图片时,按键中的keyLabel的大小
android:popupLayout 弹出键盘的布局文件
android:verticalCorrection 补偿触摸Y坐标的偏移量,用于偏移校正

基本实现

一、定义键盘的键

自己定义的xml键盘布局位于res–>xml文件目录下


这里写图片描述

键盘上键的细节和它的位置我们指定在一个xml文件中,每一个键都有自己的属性。

  • keyLabel 这个属性是指每个键显示的文本
  • codes 这个属性是指这个键代表的字符的unicode

比如我们自己定义一个数字1,则他的codes属性的值是49,keyLabel属性的值就是1。

如果一个code对应多个key,这个key代表的字符取决于这个key接受到的点击数taps,例如,一个键具有49,50,51编码:

  • 一次点击就是 1
  • 两次点击就是 2
  • 三次点击就是 3

每个键都可以设置自己的属性,这里就不一一赘述了。当然,一般情况下键盘上每行的按键尽量都控制10个或10个以内,要不然影响用户体验,每行都使用进行分行。

一般自己定义的code都为负数,比如-5代表删除,-1代表shift切换等。

数字键盘number.xml

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
          android:keyHeight="40dip"
          android:keyWidth="8.33334444%p"
          android:verticalGap="6dp">
    <Row>
        <Key android:codes="49" android:horizontalGap="2dp" android:keyEdgeFlags="left"
             android:keyLabel="1"/>
        <Key android:codes="50" android:horizontalGap="6dp" android:keyLabel="2"/>
        <Key android:codes="51" android:horizontalGap="6dp" android:keyLabel="3"/>
        <Key android:codes="52" android:horizontalGap="6dp" android:keyLabel="4"/>
        <Key android:codes="53" android:horizontalGap="6dp" android:keyLabel="5"/>
        <Key android:codes="54" android:horizontalGap="6dp" android:keyLabel="6"/>
        <Key android:codes="55" android:horizontalGap="6dp" android:keyLabel="7"/>
        <Key android:codes="56" android:horizontalGap="6dp" android:keyLabel="8"/>
        <Key android:codes="57" android:horizontalGap="6dp" android:keyLabel="9"/>
        <Key android:codes="48" android:horizontalGap="6dp" android:keyEdgeFlags="right"
             android:keyLabel="0"/>
    </Row>
    <Row>
        <Key android:codes="45" android:keyEdgeFlags="left" android:horizontalGap="2dp"
             android:keyLabel="-"/>
        <Key android:codes="47" android:horizontalGap="6dp" android:keyLabel="/"/>
        <Key android:codes="58" android:horizontalGap="6dp" android:keyLabel=":"/>
        <Key android:codes="59" android:horizontalGap="6dp" android:keyLabel=";"/>
        <Key android:codes="40" android:horizontalGap="6dp" android:keyLabel="("/>
        <Key android:codes="41" android:horizontalGap="6dp" android:keyLabel=")"/>
        <Key android:codes="165" android:horizontalGap="6dp" android:keyLabel="¥"/>
        <Key android:codes="64" android:horizontalGap="6dp" android:keyLabel="\@"/>
        <Key android:codes="8220" android:horizontalGap="6dp" android:keyLabel="“"/>
        <Key android:codes="8221" android:horizontalGap="6dp" android:keyEdgeFlags="right"
             android:keyLabel="”"/>
    </Row>
    <Row>
        <Key android:codes="-7" android:keyEdgeFlags="left" android:horizontalGap="2dp"
             android:keyLabel="#+="
             android:keyWidth="11.000002%p"/>
        <Key android:codes="12290" android:horizontalGap="14dp" android:keyLabel="。"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="65292" android:keyLabel="," android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="65311" android:keyLabel="?" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="65281" android:keyLabel="!" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="46" android:keyLabel="." android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="96" android:keyLabel="`" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="36" android:keyLabel="$" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="-5"
             android:keyEdgeFlags="right"
             android:horizontalGap="14dp"
             android:keyIcon="@drawable/delete"
             android:keyWidth="11.000002%p"/>
    </Row>
    <Row android:rowEdgeFlags="bottom">
        <Key android:codes="-2" android:keyLabel="abc" android:keyEdgeFlags="left"
             android:horizontalGap="2dp"
             android:keyWidth="11.000002%p"/>
        <Key android:codes="44" android:keyLabel="," android:horizontalGap="6dp"
             android:keyWidth="8.999998%p"/>
        <Key android:codes="-11" android:keyLabel="←" android:horizontalGap="6dp"
             android:keyWidth="8.999998%p"/>
        <Key android:codes="32" android:isRepeatable="true" android:horizontalGap="6dp"
             android:keyIcon="@drawable/space"
             android:keyWidth="20.999996%p"/>
        <Key android:codes="-12" android:horizontalGap="6dp" android:keyLabel="→"
             android:keyWidth="8.999998%p"/>
        <Key android:codes="46" android:keyLabel="." android:horizontalGap="6dp"
             android:keyWidth="8.999998%p"/>
        <Key android:codes="-3" android:keyEdgeFlags="right" android:keyLabel="完成"
             android:horizontalGap="6dp"
            android:keyWidth="20.000002%p"/>
    </Row>
</Keyboard>

英文键盘letter.xml

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
          android:keyHeight="40dip"
          android:keyWidth="8.33334444%p"
          android:verticalGap="6dp">
    <Row>
        <Key android:codes="113" android:horizontalGap="2dp"
             android:keyEdgeFlags="left" android:keyLabel="q"/>
        <Key android:codes="119" android:horizontalGap="6dp" android:keyLabel="w"/>
        <Key android:codes="101" android:horizontalGap="6dp" android:keyLabel="e"/>
        <Key android:codes="114" android:horizontalGap="6dp" android:keyLabel="r"/>
        <Key android:codes="116" android:horizontalGap="6dp" android:keyLabel="t"/>
        <Key android:codes="121" android:horizontalGap="6dp" android:keyLabel="y"/>
        <Key android:codes="117" android:horizontalGap="6dp" android:keyLabel="u"/>
        <Key android:codes="105" android:horizontalGap="6dp" android:keyLabel="i"/>
        <Key android:codes="111" android:horizontalGap="6dp" android:keyLabel="o"/>
        <Key android:codes="112" android:horizontalGap="6dp" android:keyEdgeFlags="right"
            android:keyLabel="p"/>
    </Row>
    <Row>
        <Key android:codes="97" android:horizontalGap="4.999995%p"
             android:keyEdgeFlags="left" android:keyLabel="a"/>
        <Key android:codes="115" android:horizontalGap="6dp" android:keyLabel="s"/>
        <Key android:codes="100" android:horizontalGap="6dp" android:keyLabel="d"/>
        <Key android:codes="102" android:horizontalGap="6dp" android:keyLabel="f"/>
        <Key android:codes="103" android:horizontalGap="6dp" android:keyLabel="g"/>
        <Key android:codes="104" android:horizontalGap="6dp" android:keyLabel="h"/>
        <Key android:codes="106" android:horizontalGap="6dp" android:keyLabel="j"/>
        <Key android:codes="107" android:horizontalGap="6dp" android:keyLabel="k"/>
        <Key android:codes="108" android:horizontalGap="6dp"
            android:keyEdgeFlags="right" android:keyLabel="l"/>
    </Row>
    <Row>
        <Key android:codes="-1" android:keyEdgeFlags="left" android:horizontalGap="2dp"
            android:keyIcon="@drawable/shift" android:keyWidth="11.000002%p"/>
        <Key android:codes="122" android:horizontalGap="14dp"
            android:keyLabel="z" android:keyWidth="8.33334444%p"/>
        <Key android:codes="120" android:keyLabel="x"
            android:horizontalGap="6dp" android:keyWidth="8.33334444%p"/>
        <Key android:codes="33" android:keyLabel="c"
            android:horizontalGap="6dp" android:keyWidth="8.33334444%p"/>
        <Key android:codes="118" android:keyLabel="v"
            android:horizontalGap="6dp" android:keyWidth="8.33334444%p"/>
        <Key android:codes="98" android:keyLabel="b"
            android:horizontalGap="6dp" android:keyWidth="8.33334444%p"/>
        <Key android:codes="110" android:keyLabel="n"
            android:horizontalGap="6dp" android:keyWidth="8.33334444%p"/>
        <Key android:codes="109" android:keyLabel="m"
            android:horizontalGap="6dp" android:keyWidth="8.33334444%p"/>
        <Key android:codes="-5" android:keyEdgeFlags="right" android:horizontalGap="14dp"
            android:keyIcon="@drawable/delete" android:keyWidth="11.000002%p"/>
    </Row>
    <Row android:rowEdgeFlags="bottom">
        <Key android:codes="-2" android:keyLabel="123" android:keyEdgeFlags="left"
            android:horizontalGap="2dp" android:keyWidth="11.000002%p"/>
        <Key android:codes="44" android:keyLabel=","
            android:horizontalGap="6dp" android:keyWidth="8.999998%p"/>
        <Key android:codes="-11" android:keyLabel="←"
            android:horizontalGap="6dp" android:keyWidth="8.999998%p"/>
        <Key android:codes="32" android:isRepeatable="true" android:horizontalGap="6dp"
            android:keyIcon="@drawable/space" android:keyWidth="20.999996%p"/>
        <Key android:codes="-12" android:horizontalGap="6dp"
             android:keyLabel="→" android:keyWidth="8.999998%p"/>
        <Key android:codes="46" android:keyLabel="."
            android:horizontalGap="6dp" android:keyWidth="8.999998%p"/>
        <Key android:codes="-3" android:keyEdgeFlags="right" android:keyLabel="完成"
            android:horizontalGap="6dp" android:keyWidth="20.000002%p"/>
    </Row>
</Keyboard>

符号键盘symbol.xml

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
          android:keyHeight="40dip"
          android:keyWidth="8.33334444%p"
          android:verticalGap="6dp">
    <Row>
        <Key android:codes="12304" android:horizontalGap="2dp" android:keyEdgeFlags="left"
             android:keyLabel="【"/>
        <Key android:codes="12305" android:horizontalGap="6dp" android:keyLabel="】"/>
        <Key android:codes="123" android:horizontalGap="6dp" android:keyLabel="{"/>
        <Key android:codes="125" android:horizontalGap="6dp" android:keyLabel="}"/>
        <Key android:codes="35" android:horizontalGap="6dp" android:keyLabel="#"/>
        <Key android:codes="37" android:horizontalGap="6dp" android:keyLabel="%"/>
        <Key android:codes="94" android:horizontalGap="6dp" android:keyLabel="^"/>
        <Key android:codes="42" android:horizontalGap="6dp" android:keyLabel="*"/>
        <Key android:codes="43" android:horizontalGap="6dp" android:keyLabel="+"/>
        <Key android:codes="61" android:horizontalGap="6dp" android:keyEdgeFlags="right"
             android:keyLabel="="/>
    </Row>
    <Row>
        <Key android:codes="95" android:keyEdgeFlags="left" android:horizontalGap="2dp"
             android:keyLabel="_"/>
        <Key android:codes="-9" android:horizontalGap="6dp" android:keyLabel="——"/>
        <Key android:codes="92" android:horizontalGap="6dp" android:keyLabel="\"/>
        <Key android:codes="124" android:horizontalGap="6dp" android:keyLabel="|"/>
        <Key android:codes="126" android:horizontalGap="6dp" android:keyLabel="~"/>
        <Key android:codes="12298" android:horizontalGap="6dp" android:keyLabel="《"/>
        <Key android:codes="12299" android:horizontalGap="6dp" android:keyLabel="》"/>
        <Key android:codes="36" android:horizontalGap="6dp" android:keyLabel="$"/>
        <Key android:codes="38" android:horizontalGap="6dp" android:keyLabel="&amp;"/>
        <Key android:codes="46" android:horizontalGap="6dp" android:keyEdgeFlags="right"
             android:keyLabel="·"/>
    </Row>
    <Row>
        <Key android:codes="-7" android:keyEdgeFlags="left" android:horizontalGap="2dp"
             android:keyLabel="123"
             android:keyWidth="11.000002%p"/>
        <Key android:codes="-8" android:horizontalGap="14dp" android:keyLabel="..."
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="44" android:keyLabel="," android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="-10" android:keyLabel="^_^" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="63" android:keyLabel="\?" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="33" android:keyLabel="!" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="-13" android:keyLabel="^o^" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="-14" android:keyLabel="&gt;_&lt;" android:horizontalGap="6dp"
             android:keyWidth="8.33334444%p"/>
        <Key android:codes="-5" android:keyEdgeFlags="right" android:horizontalGap="14dp"
             android:keyIcon="@drawable/delete"
             android:keyWidth="11.000002%p"/>
    </Row>
    <Row android:rowEdgeFlags="bottom">
        <Key android:codes="-2" android:keyLabel="abc" android:keyEdgeFlags="left"
             android:horizontalGap="2dp"
             android:keyWidth="11.000002%p"/>
        <Key android:codes="44" android:keyLabel="," android:horizontalGap="6dp"
             android:keyWidth="8.999998%p"/>
        <Key android:codes="-11" android:keyLabel="←" android:horizontalGap="6dp"
             android:keyWidth="8.999998%p"/>
        <Key android:codes="32" android:isRepeatable="true" android:horizontalGap="6dp"
             android:keyIcon="@drawable/space"
             android:keyWidth="20.999996%p"/>
        <Key android:codes="-12" android:horizontalGap="6dp" android:keyLabel="→"
             android:keyWidth="8.999998%p"/>
        <Key android:codes="46" android:keyLabel="." android:horizontalGap="6dp"
             android:keyWidth="8.999998%p"/>
        <Key android:codes="-3" android:keyEdgeFlags="right" android:keyLabel="完成"
             android:horizontalGap="6dp"
             android:keyWidth="20.000002%p"/>
    </Row>
</Keyboard>

二、处理按键

OnKeyboardActionListener

在KeyboardView类里面有专门处理Keyboard的监听类OnKeyboardActionListener

public class KeyboardView extends View implements View.OnClickListener {

    ......

    /**
     * Listener for virtual keyboard events.
     */
    public interface OnKeyboardActionListener {

        /**
         * 当用户按下一个键时调用。 这是在调用onKey之前。
         * 对于重复的键,此键仅调用一次。
         * @param primaryCode被按下的键的unicode。如果触摸不在有效范围内,值将为零。
         */
        void onPress(int primaryCode);

        /**
         * 当用户释放键时调用。 这是在调用onKey之后。
         * 对于重复的键,此键仅调用一次。
         * @param primaryCode被释放的键的unicode
         */
        void onRelease(int primaryCode);

        /**
         * 发送一个按键到监听器
         * @ param primaryCode这是按下的键
         * @ param keyCodes所有可能的替代键的代码,
         */
        void onKey(int primaryCode, int[] keyCodes);

        /**
         * 向侦听器发送一系列字符。
         * @param text 要显示的字符序列。
         */
        void onText(CharSequence text);

        /**
         * 当用户从右向左快速移动手指时调用。
         */
        void swipeLeft();

        /**
         * 当用户从左向右快速移动手指时调用。
         */
        void swipeRight();

        /**
         * 当用户从上到下快速移动手指时调用。
         */
        void swipeDown();

        /**
         * 当用户快速将手指从下向上移动时调用。
         */
        void swipeUp();
    }

    ......

}

我们自己实现OnKeyboardActionListener接口,即可处理对键盘的操作。主要实现了onKey方法。在这个方法里通过传入的primaryCode进行相应的操作,如

  • 如果code是 KEYCODE_DELETE 使用Editable.delete方法删除光标左边的字符
  • 如果code是 KEYCODE_SHIFT boolean类型的isUpper的值会被改变,并且使用 setShifted() 方法改变键盘的换档状态(shift state),当状态改变时,键盘需要重绘,所以的键的label被更新了,invalidateAllKeys() 方法用来重绘所有的键
  • 对于其他所有的codes,只是简单的将unicode转化为字符并且使用Editable.insert()方法插入到输入框里即可,如果这个code代表了字母表里的一个字母,并且isUpper变量为true,那么还需要将字母转化为大写
  • 若code为负数的话,只需要根据自己的定义,进行相应的处理即可,例如-8代表省略号,-10代表笑脸等。
public class KeyboardUtil {

    ...

    private static final int SYMBOL_CODE = -7;//符号键盘
    private static final int ELLIPSES_CODE = -8;//省略号
    private static final int CHINESE_HORIZONTAL_LINE_CODE = -9;//中文横线
    private static final int SMILING_FACE_CODE = -10;//笑脸
    private static final int LEFT_CODE = -11;//中文横线
    private static final int RIGHT_CODE = -12;//中文横线
    private static final int HEE_CODE = -13;//哈哈
    private static final int AWKWARD_CODE = -14;//尴尬

 OnKeyboardActionListener onKeyboardActionListener = new OnKeyboardActionListener() {
        @Override
        public void swipeUp() {
        }

        @Override
        public void swipeRight() {
        }

        @Override
        public void swipeLeft() {
        }

        @Override
        public void swipeDown() {
        }

        @Override
        public void onText(CharSequence text) {
        }

        @Override
        public void onRelease(int primaryCode) {
        }

        @Override
        public void onPress(int primaryCode) {
        }

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            Editable editable = ed.getText();
            int start = ed.getSelectionStart();
            if (primaryCode == Keyboard.KEYCODE_CANCEL) {// 完成
                hideKeyboard();
            } else if (primaryCode == Keyboard.KEYCODE_DELETE) {// 回退
                if (editable != null && editable.length() > 0) {
                    if (start > 0) {
                        editable.delete(start - 1, start);
                    }
                }
            } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {// 大小写切换
                isUpper = !isUpper;
                k1.setShifted(isUpper);
                keyboardView.invalidateAllKeys();
            } else if (primaryCode == SYMBOL_CODE) {// 符号键盘
                if (isSymbol) {
                    isSymbol = false;
                    keyboardView.setKeyboard(k2);
                } else {
                    isSymbol = true;
                    keyboardView.setKeyboard(k3);
                }
            } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {// 数字键盘切换
                if (isNum) {
                    isNum = false;
                    keyboardView.setKeyboard(k1);
                } else {
                    isNum = true;
                    keyboardView.setKeyboard(k2);
                }
            } else if (primaryCode == LEFT_CODE) { //向左
                if (start > 0) {
                    ed.setSelection(start - 1);
                }
            } else if (primaryCode == RIGHT_CODE) { // 向右
                if (start < ed.length()) {
                    ed.setSelection(start + 1);
                }
            } else if (primaryCode == ELLIPSES_CODE) { //省略号
                editable.insert(start, "...");
            } else if (primaryCode == CHINESE_HORIZONTAL_LINE_CODE) {
                editable.insert(start, "——");
            } else if (primaryCode == SMILING_FACE_CODE) {
                editable.insert(start, "^_^");
            } else if (primaryCode == HEE_CODE) {
                editable.insert(start, "^o^");
            } else if (primaryCode == AWKWARD_CODE) {
                editable.insert(start, ">_<");
            } else {
                String str = Character.toString((char) primaryCode);
                if (isWord(str)) {
                    if (isUpper) {
                        str = str.toUpperCase();
                    } else {
                        str = str.toLowerCase();
                    }
                }
                editable.insert(start, str);

            }
        }
    };

    ...

}

KeyboardUtil

这里自定义了一个键盘的工具类KeyboardUtil

import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class KeyboardUtil {
    private KeyboardView keyboardView;
    private Keyboard k1;// 字母键盘
    private Keyboard k2;// 数字键盘
    private Keyboard k3;// 符号键盘
    private boolean isNum = false;// 是否数据键盘
    private boolean isUpper = false;// 是否大写
    private boolean isSymbol = false;// 是否符号

    private static final int SYMBOL_CODE = -7;//符号键盘
    private static final int ELLIPSES_CODE = -8;//省略号
    private static final int CHINESE_HORIZONTAL_LINE_CODE = -9;//中文横线
    private static final int SMILING_FACE_CODE = -10;//笑脸
    private static final int LEFT_CODE = -11;//中文横线
    private static final int RIGHT_CODE = -12;//中文横线
    private static final int HEE_CODE = -13;//哈哈
    private static final int AWKWARD_CODE = -14;//尴尬

    private ViewGroup rootView;
    private EditText ed;

    private KeyboardUtil(Activity activity, EditText edit) {
        this.ed = edit;
        k1 = new Keyboard(activity, R.xml.letter);
        k2 = new Keyboard(activity, R.xml.number);
        k3 = new Keyboard(activity, R.xml.symbol);

        keyboardView = new KeyboardView(activity, null);
        keyboardView.setKeyboard(k1);
        keyboardView.setEnabled(true);
        keyboardView.setPreviewEnabled(false);
        keyboardView.setOnKeyboardActionListener(onKeyboardActionListener);

        rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);

    }

    OnKeyboardActionListener onKeyboardActionListener = new OnKeyboardActionListener() {
        @Override
        public void swipeUp() {
        }

        @Override
        public void swipeRight() {
        }

        @Override
        public void swipeLeft() {
        }

        @Override
        public void swipeDown() {
        }

        @Override
        public void onText(CharSequence text) {
        }

        @Override
        public void onRelease(int primaryCode) {
        }

        @Override
        public void onPress(int primaryCode) {
        }

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            Editable editable = ed.getText();
            int start = ed.getSelectionStart();
            if (primaryCode == Keyboard.KEYCODE_CANCEL) {// 完成
                hideKeyboard();
            } else if (primaryCode == Keyboard.KEYCODE_DELETE) {// 回退
                if (editable != null && editable.length() > 0) {
                    if (start > 0) {
                        editable.delete(start - 1, start);
                    }
                }
            } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {// 大小写切换
                isUpper = !isUpper;
                k1.setShifted(isUpper);
                keyboardView.invalidateAllKeys();
            } else if (primaryCode == SYMBOL_CODE) {// 符号键盘
                if (isSymbol) {
                    isSymbol = false;
                    keyboardView.setKeyboard(k2);
                } else {
                    isSymbol = true;
                    keyboardView.setKeyboard(k3);
                }
            } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {// 数字键盘切换
                if (isNum) {
                    isNum = false;
                    keyboardView.setKeyboard(k1);
                } else {
                    isNum = true;
                    keyboardView.setKeyboard(k2);
                }
            } else if (primaryCode == LEFT_CODE) { //向左
                if (start > 0) {
                    ed.setSelection(start - 1);
                }
            } else if (primaryCode == RIGHT_CODE) { // 向右
                if (start < ed.length()) {
                    ed.setSelection(start + 1);
                }
            } else if (primaryCode == ELLIPSES_CODE) { //省略号
                editable.insert(start, "...");
            } else if (primaryCode == CHINESE_HORIZONTAL_LINE_CODE) {
                editable.insert(start, "——");
            } else if (primaryCode == SMILING_FACE_CODE) {
                editable.insert(start, "^_^");
            } else if (primaryCode == HEE_CODE) {
                editable.insert(start, "^o^");
            } else if (primaryCode == AWKWARD_CODE) {
                editable.insert(start, ">_<");
            } else {
                String str = Character.toString((char) primaryCode);
                if (isWord(str)) {
                    if (isUpper) {
                        str = str.toUpperCase();
                    } else {
                        str = str.toLowerCase();
                    }
                }
                editable.insert(start, str);

            }
        }
    };

    private boolean isShow = false;

    public void showKeyboard() {
        if (!isShow) {
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, RelativeLayout.TRUE);
            rootView.addView(keyboardView, layoutParams);
            isShow = true;
        }
    }

    private void hideKeyboard() {
        if (rootView != null && keyboardView != null && isShow) {
            isShow = false;
            rootView.removeView(keyboardView);
        }
        mInstance = null;
    }

    private boolean isWord(String str) {
        return str.matches("[a-zA-Z]");
    }

    private static KeyboardUtil mInstance;

    public static KeyboardUtil shared(Activity activity, EditText edit) {
        if (mInstance == null) {
            mInstance = new KeyboardUtil(activity, edit);
        }
        mInstance.ed = edit;
        return mInstance;
    }

}

三、MainActivity中的使用

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText edit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit = (EditText) this.findViewById(R.id.edit);
        edit.setInputType(InputType.TYPE_NULL);

        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyboardUtil.shared(MainActivity.this,edit).showKeyboard();
            }
        });
    }
}

好了,关于Android的自定义键盘就说到这里,这个只是自定义键盘最简单的使用方式。当然,就算是最简单的方式,想要完整的实现下来也是踩了不少坑的。有时间了在继续踩。这里贴上源码下载

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

推荐阅读更多精彩内容