創建安卓鍵盤演示——改爲 XML 佈局

續前文:創建安卓鍵盤演示——“好不”

因爲一些 UI 元素的屬性似乎只有在 XML 中才能設置,於是先摸索一下如何使用 XML 佈局代替原本在 Java 代碼中初始化 UI。

xml/keyboard.xml:

<Row>
    <Key
        android:codes="1"
        android:keyLabel="好" />
    <Key
        android:codes="2"
        android:keyLabel="不" />
</Row>

layout/keyboard_view.xml (值得一提,KeyboardViewKeyboard 在最新的 API 29 中已作廢)

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</android.inputmethodservice.KeyboardView>

Java 部分相應修改:

public class 好不鍵盤 extends InputMethodService implements KeyboardView.OnKeyboardActionListener {

    private static final String 字符 = "@好不";

    @Override
    public View onCreateInputView() {
        KeyboardView 視圖 = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
        Keyboard 鍵盤 = new Keyboard(this, R.xml.keyboard);
        視圖.setKeyboard(鍵盤);
        視圖.setOnKeyboardActionListener(this);
        return 視圖;
    }

    @Override
    public void onKey(int, int[] keyCodes) {
        InputConnection 輸入連接 = getCurrentInputConnection();

        if (輸入連接 != null) {
            char= 字符.charAt();
            輸入連接.commitText(String.valueOf(), 1);
        }
    }
//...一堆空的重寫方法
}

效果差很多,還需研究如何設置風格:
在這裏插入圖片描述

參考

Learn to create a System Keyboard on Android

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章