天天看點

Android自定義鍵盤的簡單實作概述基本實作

概述

突然發現好多軟體都使用了自己定義的軟鍵盤。自己就想着先把這塊坑先踩踩把,以後掉坑的時候不至于帥的太慘。言歸正傳,對于自定義軟鍵盤。需要用到系統提供的兩個類: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檔案目錄下

Android自定義鍵盤的簡單實作概述基本實作

鍵盤上鍵的細節和它的位置我們指定在一個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 = -;//符号鍵盤
    private static final int ELLIPSES_CODE = -;//省略号
    private static final int CHINESE_HORIZONTAL_LINE_CODE = -;//中文橫線
    private static final int SMILING_FACE_CODE = -;//笑臉
    private static final int LEFT_CODE = -;//中文橫線
    private static final int RIGHT_CODE = -;//中文橫線
    private static final int HEE_CODE = -;//哈哈
    private static final int AWKWARD_CODE = -;//尴尬

 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() > ) {
                    if (start > ) {
                        editable.delete(start - , 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 > ) {
                    ed.setSelection(start - );
                }
            } else if (primaryCode == RIGHT_CODE) { // 向右
                if (start < ed.length()) {
                    ed.setSelection(start + );
                }
            } 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 = -;//符号鍵盤
    private static final int ELLIPSES_CODE = -;//省略号
    private static final int CHINESE_HORIZONTAL_LINE_CODE = -;//中文橫線
    private static final int SMILING_FACE_CODE = -;//笑臉
    private static final int LEFT_CODE = -;//中文橫線
    private static final int RIGHT_CODE = -;//中文橫線
    private static final int HEE_CODE = -;//哈哈
    private static final int AWKWARD_CODE = -;//尴尬

    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();

    }

    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() > ) {
                    if (start > ) {
                        editable.delete(start - , 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 > ) {
                    ed.setSelection(start - );
                }
            } else if (primaryCode == RIGHT_CODE) { // 向右
                if (start < ed.length()) {
                    ed.setSelection(start + );
                }
            } 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自定義鍵盤的簡單實作概述基本實作

好了,關于Android的自定義鍵盤就說到這裡,這個隻是自定義鍵盤最簡單的使用方式。當然,就算是最簡單的方式,想要完整的實作下來也是踩了不少坑的。有時間了在繼續踩。這裡貼上源碼下載下傳