Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義軟鍵盤實戰:從數字鍵盤到漢字鍵盤

編輯:關於 Android 程式設計

一、軟鍵盤的兩塊基石

實現自定義軟鍵盤,主要依賴系統提供的兩個類:Keyboard 與 KeyboardView。

Keyboard 負責描述鍵盤的鍵位數據,官方說法是「虛擬鍵盤事件的監聽器」;KeyboardView 則負責渲染與觸摸檢測,官方描述為「渲染一個虛擬 Keyboard,處理按鍵繪製以及按鍵按下和觸摸移動的檢測」。鍵盤絕大多數可配置項,都要通過 KeyboardView 設置:

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 文件夾,並在其中創建 symbols.xml。每個按鍵都帶有一個 codes 值,代碼中正是依據它來判斷按下了哪個鍵。

<?xml version="1.0" encoding="utf-8"?>
<keyboard xmlns:android="https://schemas.android.com/apk/res/android"
    android:horizontalGap="0px"
    android:verticalGap="0px"
    android:keyWidth="20%p"
    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="9" />
        <key android:codes="48" android:keyLabel="0" />
        <key android:codes="46" android:keyLabel="." />
        <key android:codes="-3" android:isRepeatable="true" android:keyLabel="完成" android:keyWidth="40%p" />
    </row>
</keyboard>

數字鍵盤界面如下:

結構上,keyboard 說明這是鍵盤定義文件,row 是一行按鍵,key 是單個按鍵。常用屬性如下:

codes:按鍵輸出的鍵碼,可以是 Unicode 值、逗號分隔的多個值(長按可在多值間切換),也可以是字符串,字符串中的特殊字符需用反斜槓轉義,如 \n 或 \uxxxx。上例中數字 1 對應 49。
keyLabel:按鍵上顯示的文本。
keyIcon:按鍵上顯示的圖標,一旦指定則以圖片呈現,不再顯示文本。
keyWidth / keyHeight:按鍵寬高,支持 px、in 等精確單位,也支持百分比,以 % 結尾表示相對於自身基準,以 %p 結尾表示相對於父容器。
horizontalGap:按鍵的水平間距,取值規則同上。
isSticky:是否為粘滯鍵,例如 Shift 大小寫切換鍵就具有按下與正常兩種狀態。
isModifier:是否為功能鍵(如 Alt、Shift)。
keyOutputText:按鍵輸出的文本內容。
isRepeatable:長按是否觸發重複按鍵事件。
keyEdgeFlags:按鍵對齊方式,取值 left 或 right。

系統預留了一批負數鍵碼常量,用於表示特殊功能鍵:

public static final int KEYCODE_SHIFT = -1;
public static final int KEYCODE_MODE_CHANGE = -2;
public static final int KEYCODE_CANCEL = -3;
public static final int KEYCODE_DONE = -4;
public static final int KEYCODE_DELETE = -5;
public static final int KEYCODE_ALT = -6;

因此回退鍵可以寫成:

<key android:codes="-5" android:keyIcon="@drawable/sym_keyboard_delete" />

對應的監聽判斷就是:

if (primaryCode == Keyboard.KEYCODE_DELETE) { }

三、漢字鍵盤的布局

再在 xml 文件夾中新建 chinese.xml。與數字鍵盤不同,這裡每個按鍵的 codes 就是該漢字在 UTF-16 中的編碼值。

查編碼有兩條路。第一條是直接查 UTF-16 碼表,但漢字一多,逐個對照填入 XML 就變成體力活了。第二條更貼合程序員習慣——寫幾行代碼讓機器生成:

// 取得字符對應的 codes
char c;
int i;
String[] strings = { "一", "二", "三", "四", "五", "六", "年", "級", "班", "." };
for (String str : strings) {
    c = str.toCharArray()[0];
    i = c;
    Log.i("key", "<key android:codes=\"" + i + "\" android:keyLabel=\"" + c + "\" />");
}

這樣就得到了符合 XML 格式的鍵位語句。剩下的問題是 logcat 輸出裡混雜著時間與等級前綴:

07-16 18:20:12.220: I/key(5200): <key android:codes="29677" android:keyLabel="班" />

把日志導出到文本文件,用編輯器將 07-16 18:20:12.220: I/key(5200): 這段前綴批量替換為 8 個空格即可——用 8 個空格是為了讓 XML 的縮排對齊美觀。

最終的 chinese.xml 大致如下:

<?xml version="1.0" encoding="UTF-8"?>
<keyboard xmlns:android="https://schemas.android.com/apk/res/android"
    android:horizontalGap="0.0px"
    android:verticalGap="0.0px"
    android:keyWidth="25.000002%p"
    android:keyHeight="@dimen/key_height">
    <row>
        <key android:codes="19968" android:keyLabel="一" />
        <key android:codes="20108" android:keyLabel="二" />
        <key android:codes="19977" android:keyLabel="三" />
        <key android:codes="-5" android:isRepeatable="true" android:keyIcon="@drawable/sym_keyboard_delete" />
    </row>
    <row>
        <key android:codes="22235" android:keyLabel="四" />
        <key android:codes="20116" android:keyLabel="五" />
        <key android:codes="20845" android:keyLabel="六" />
        <key android:codes="-2" android:keyLabel="數字" />
    </row>
    <row>
        <key android:codes="24180" android:keyLabel="年" />
        <key android:codes="32423" android:keyLabel="級" />
        <key android:codes="29677" android:keyLabel="班" />
        <key android:codes="-3" android:keyEdgeFlags="right" android:keyLabel="完成" android:keyWidth="25.000004%p" />
    </row>
</keyboard>

中文鍵盤最終畫面如下:

四、鍵盤事件處理

新建 KeyboardUtil.java 統一封裝鍵盤行為,內部同時持有中文鍵盤與數字鍵盤兩個 Keyboard 對象,並通過狀態標志控制當前顯示哪一套。

public class KeyboardUtil {

    private Context ctx;
    private Activity act;
    private KeyboardView keyboardView;
    private Keyboard k1; // 中文鍵盤
    private Keyboard k2; // 數字鍵盤
    public boolean isNumber = false; // 是否數字鍵盤
    public boolean isUpper = false;  // 是否大寫
    private EditText ed;

    public KeyboardUtil(Activity act, Context ctx, EditText edit) {
        this.act = act;
        this.ctx = ctx;
        this.ed = edit;
        k1 = new Keyboard(ctx, R.xml.chinese);
        k2 = new Keyboard(ctx, R.xml.symbols);
        keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
        keyboardView.setKeyboard(k1);
        keyboardView.setEnabled(true);
        keyboardView.setPreviewEnabled(true);
        keyboardView.setOnKeyboardActionListener(listener);
    }

    private OnKeyboardActionListener listener = new OnKeyboardActionListener() {
        public void swipeUp() { }
        public void swipeRight() { }
        public void swipeLeft() { }
        public void swipeDown() { }
        public void onText(CharSequence text) { }
        public void onRelease(int primaryCode) { }
        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 && start > 0) {
                    editable.delete(start - 1, start);
                }
            } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {    // 大小寫切換
                changeKey();
                keyboardView.setKeyboard(k1);
            } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE) { // 鍵盤切換
                isNumber = !isNumber;
                keyboardView.setKeyboard(isNumber ? k2 : k1);
            } else if (primaryCode == 57419) {                     // 左移光標
                if (start > 0) ed.setSelection(start - 1);
            } else if (primaryCode == 57421) {                     // 右移光標
                if (start < ed.length()) ed.setSelection(start + 1);
            } else {
                editable.insert(start, Character.toString((char) primaryCode));
            }
        }
    };

    /** 鍵盤大小寫切換 */
    private void changeKey() {
        List<Keyboard.Key> keylist = k1.getKeys();
        isUpper = !isUpper;
        for (Keyboard.Key key : keylist) {
            if (key.label != null && isword(key.label.toString())) {
                if (isUpper) {
                    key.label = key.label.toString().toUpperCase();
                    key.codes[0] = key.codes[0] - 32;
                } else {
                    key.label = key.label.toString().toLowerCase();
                    key.codes[0] = key.codes[0] + 32;
                }
            }
        }
    }

    public void showKeyboard() {
        if (keyboardView.getVisibility() != View.VISIBLE) {
            keyboardView.setVisibility(View.VISIBLE);
        }
    }

    public void hideKeyboard() {
        if (keyboardView.getVisibility() == View.VISIBLE) {
            keyboardView.setVisibility(View.INVISIBLE);
        }
    }

    private boolean isword(String str) {
        return "abcdefghijklmnopqrstuvwxyz".indexOf(str.toLowerCase()) > -1;
    }

    public void showChinese() {
        showKeyboard();
        isNumber = false;
        keyboardView.setKeyboard(k1);
    }

    public void showNumber() {
        showKeyboard();
        isNumber = true;
        keyboardView.setKeyboard(k2);
    }
}

五、主界面布局

界面並不複雜:兩個輸入框,一個填班級(中文),一個填分數(數字),再加一個平時隱藏的 KeyboardView。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:id="@+id/ll_hint"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_class"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:text="班級"
            android:textSize="20dip" />
        <TextView
            android:id="@+id/tv_score"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:layout_weight="1"
            android:text="得分"
            android:textSize="20dip" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/ll_hint"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/edit_class"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="請輸入班級" />
        <EditText
            android:id="@+id/edit_score"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="請輸入分數" />
    </LinearLayout>
</RelativeLayout>

六、Activity 中的收尾工作

最後在 Activity 裡禁用系統輸入法、屏蔽長按選擇菜單,並且在輸入框被觸摸時彈出自定義鍵盤。關鍵片段如下:

// 屏蔽系統默認軟鍵盤
if (android.os.Build.VERSION.SDK_INT <= 10) {
    edit_class.setInputType(InputType.TYPE_NULL);
} else {
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    try {
        Method m = EditText.class.getMethod("setShowSoftInputOnFocus", boolean.class);
        m.setAccessible(true);
        m.invoke(edit_class, false);
        m.invoke(edit_score, false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

// 屏蔽長按彈出的 ActionMode 菜單
edit_class.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
    public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; }
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; }
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; }
    public void onDestroyActionMode(ActionMode mode) { }
});

// 點擊輸入框時彈出自定義鍵盤
edit_class.setOnTouchListener((v, event) -> {
    new KeyboardUtil(act, ctx, edit_class).showChinese();
    return false;
});
edit_score.setOnTouchListener((v, event) -> {
    new KeyboardUtil(act, ctx, edit_score).showNumber();
    return false;
});

最後的運行界面如下:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved