續前文:創建安卓鍵盤演示——“好不”
因爲一些 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 (值得一提,KeyboardView 和 Keyboard 在最新的 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);
}
}
//...一堆空的重寫方法
}
效果差很多,還需研究如何設置風格: