編輯:關於 Android 開發
在 Android 開發中,除了系統預設的輸入法,我們其實可以自己打造一個完全自訂的軟鍵盤。它並不像想像中那麼複雜,只要掌握幾個核心概念就能動手實作。
整體思路可以濃縮成四個步驟:
1. 軟鍵盤的本質是一個檢視元件,透過 android.inputmethodservice.KeyboardView 這個類別來呈現。
2. 在主版面配置中使用 FrameLayout(格線配置),需要顯示鍵盤時把它設為可見,不需要時設為隱藏。
3. 撰寫 XML 檔案來描述鍵盤的按鍵內容,再用這些 XML 資源去填充 KeyboardView。
4. 為 EditText 註冊監聽事件,把使用者的輸入串接起來。
完成以上四點,鍵盤就算開發完成了。
先來看效果示意圖:

KeyboardView 是官方用來渲染虛擬鍵盤的檢視元件,它負責按鍵的繪製以及觸控事件的判斷。想深入了解自訂鍵盤的行為,直接閱讀它的原始碼會很有幫助:
package android.inputmethodservice;
/**
* A view that renders a virtual {@link Keyboard}. It handles rendering of keys and
* detecting key presses and touch movements.
*/
public class KeyboardView extends View implements View.OnClickListener {
public interface OnKeyboardActionListener {
void onPress(int primaryCode);
void onRelease(int primaryCode);
void onKey(int primaryCode, int[] keyCodes);
void onText(CharSequence text);
void swipeLeft();
void swipeRight();
void swipeDown();
void swipeUp();
}
// 此處省略大量渲染與事件處理的實作細節,完整原始碼請參考 Android SDK
}
由於原始碼篇幅龐大,這裡保留關鍵結構。讀者可自行下載完整原始碼深入研究。
主版面採用格線配置包裹一個垂直的 LinearLayout,裡面放兩個 EditText,並用 include 引入鍵盤的版面配置:
<framelayout android:layout_height="match_parent" android:layout_width="match_parent" tools:context=".MainActivity" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools">
<!--鍵盤是個控件 我們需要時填充布局進去 顯示鍵盤-->
<linearlayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical">
<edittext android:background="#00dfef" android:focusable="true" android:focusableintouchmode="true" android:hint="觸摸彈出自定義xml鍵盤(構造方法1)" android:id="@+id/Etext_1" android:layout_height="wrap_content" android:layout_margin="20dp" android:layout_width="match_parent" android:padding="10dp">
<edittext android:background="#00dfef" android:hint="觸摸彈出自定義xml鍵盤2(構造方法2)" android:id="@+id/Etext_2" android:layout_height="wrap_content" android:layout_margin="20dp" android:layout_width="match_parent" android:padding="10dp">
</edittext></edittext></linearlayout>
<!-- 使用xml自定義鍵盤樣式 使用KeyboardView鍵盤控件存放定義的鍵盤布局 -->
<include layout="@layout/key_board_view"></include>
</framelayout>
這個版面其實就是一個 android.inputmethodservice.KeyboardView 檢視元件,用來承載我們自訂的鍵盤配置。背景顏色與文字選擇器之類的細節讀者可依需求自行補上。
<relativelayout android:layout_height="wrap_content" android:layout_width="match_parent" xmlns:android="https://schemas.android.com/apk/res/android">
<!-- 使用 android 自帶庫中 inputmethodservice 包中 keyboardView 存放鍵盤布局 -->
</relativelayout>
鍵盤分成數字與英文兩種,設計概念參考實體電腦鍵盤,每個按鍵的 codes 值對應的是 ASCII 碼。
先定義數字鍵盤 numskeys.xml:
<keyboard android:horizontalgap="0px" android:keyheight="45dip" android:keywidth="25%p" android:verticalgap="0px" xmlns:android="https://schemas.android.com/apk/res/android">
<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="57419" android:keyedgeflags="right" android:keyicon="@mipmap/sym_keyboard_left"></key></key></key></key></row>
<row>
<key android:codes="52" android:keylabel="4"><key android:codes="53" android:keylabel="5"><key android:codes="54" android:keylabel="6"><key android:codes="57421" android:keyedgeflags="right" android:keyicon="@mipmap/sym_keyboard_right"></key></key></key></key></row>
<row>
<key android:codes="55" android:keylabel="7"><key android:codes="56" android:keylabel="8"><key android:codes="57" android:keylabel="9"><key android:codes="-3" android:isrepeatable="true" android:keyedgeflags="right" android:keyheight="100dip" android:keylabel="done"></key></key></key></key></row>
<row>
<key android:codes="-2" android:keylabel="ABC"><key android:codes="48" android:keylabel="0"><key android:codes="-5" android:keyicon="@mipmap/sym_keyboard_delete"></key></key></key>
</row>
</keyboard>
接著定義英文鍵盤 wordskeys.xml:
<keyboard android:horizontalgap="1px" android:keyheight="45dip" android:keywidth="10%p" android:verticalgap="1px" xmlns:android="https://schemas.android.com/apk/res/android">
<row>
<key android:codes="113" android:keylabel="q"><key android:codes="119" android:keylabel="w"><key android:codes="101" android:keylabel="e"><key android:codes="114" android:keylabel="r"><key android:codes="116" android:keylabel="t"><key android:codes="121" android:keylabel="y"><key android:codes="117" android:keylabel="u"><key android:codes="105" android:keylabel="i"><key android:codes="111" android:keylabel="o"><key android:codes="112" android:keylabel="p"></key></key></key></key></key></key></key></key></key></key></key></row>
<row>
<key android:codes="97" android:keylabel="a"><key android:codes="115" android:keylabel="s"><key android:codes="100" android:keylabel="d"><key android:codes="102" android:keylabel="f"><key android:codes="103" android:keylabel="g"><key android:codes="104" android:keylabel="h"><key android:codes="106" android:keylabel="j"><key android:codes="107" android:keylabel="k"><key android:codes="108" android:keyedgeflags="right" android:keylabel="l"></key></key></key></key></key></key></key></key></key></key></row>
<row>
<key android:codes="-1" android:ismodifier="true" android:issticky="true" android:keyedgeflags="left" android:keyicon="@mipmap/sym_keyboard_shift" android:keywidth="14.999998%p"><key android:codes="122" android:keylabel="z"><key android:codes="120" android:keylabel="x"><key android:codes="99" android:keylabel="c"><key android:codes="118" android:keylabel="v"><key android:codes="98" android:keylabel="b"><key android:codes="110" android:keylabel="n"><key android:codes="109" android:keylabel="m"><key android:codes="-5" android:isrepeatable="true" android:keyedgeflags="right" android:keyicon="@mipmap/sym_keyboard_delete" android:keywidth="14.999998%p"></key></key></key></key></key></key></key></key></key></key></row>
<row android:rowedgeflags="bottom">
<key android:codes="-2" android:keylabel="12#" android:keywidth="25%p"><key android:codes="44" android:keylabel="," android:keywidth="14%p"><key android:codes="32" android:isrepeatable="true" android:keyicon="@mipmap/sym_keyboard_space" android:keywidth="25%p"><key android:codes="46" android:keylabel="." android:keywidth="14%p"><key android:codes="-3" android:keyedgeflags="right" android:keylabel="done" android:keywidth="25%p"></key></key></key></key></key></row>
</keyboard>
這個類別實作了 KeyboardView.OnKeyboardActionListener 介面,負責把按鍵事件轉換成對 EditText 的操作,同時處理數字鍵與字母鍵的切換、大小寫切換等邏輯:
public class XMlKeysUtils implements KeyboardView.OnKeyboardActionListener {
private EditText editText;
private Keyboard k1, k2; // 數字鍵盤與字母鍵盤
private KeyboardView keyboardView;
private boolean isUpper = false;
private boolean isNum = false;
public XMlKeysUtils(Activity activity, EditText editText) {
this.editText = editText;
k1 = new Keyboard(activity.getApplicationContext(), R.xml.numskeys);
k2 = new Keyboard(activity.getApplicationContext(), R.xml.wordskeys);
keyboardView = (KeyboardView) activity.findViewById(R.id.my_keyboard_view);
keyboardView.setKeyboard(k1);
keyboardView.setEnabled(true);
keyboardView.setPreviewEnabled(true);
keyboardView.setOnKeyboardActionListener(this);
}
public void showKeyBoard() {
int visibility = keyboardView.getVisibility();
if (visibility == View.GONE || visibility == View.INVISIBLE) {
keyboardView.setVisibility(View.VISIBLE);
}
}
public void hideKeyBoard() {
if (keyboardView.getVisibility() == View.VISIBLE) {
keyboardView.setVisibility(View.GONE);
}
}
// 大小寫切換
public void changeKey() {
List<keyboard.key> keyList = k2.getKeys();
if (isUpper) {
isUpper = false;
for (Keyboard.Key key : keyList) {
if (key.label != null && isword(key.label.toString())) {
key.label = key.label.toString().toLowerCase();
key.codes[0] = key.codes[0] + 32;
}
}
} else {
isUpper = true;
for (Keyboard.Key key : keyList) {
if (key.label != null && isword(key.label.toString())) {
key.label = key.label.toString().toUpperCase();
key.codes[0] = key.codes[0] - 32;
}
}
}
}
private boolean isword(String str) {
String wordstr = "abcdefghijklmnopqrstuvwxyz";
return wordstr.indexOf(str.toLowerCase()) > -1;
}
@Override
public void onKey(int primaryCode, int[] keyCodes) {
Editable edittable = editText.getText();
int start = editText.getSelectionStart();
if (primaryCode == Keyboard.KEYCODE_CANCEL) {
hideKeyBoard();
} else if (primaryCode == Keyboard.KEYCODE_DELETE) {
if (edittable != null && edittable.length() > 0 && start > 0) {
edittable.delete(start - 1, start);
}
} else if (primaryCode == Keyboard.KEYCODE_SHIFT) {
changeKey();
keyboardView.setKeyboard(k2);
} else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
if (isNum) { isNum = false; keyboardView.setKeyboard(k2); }
else { isNum = true; keyboardView.setKeyboard(k1); }
} else if (primaryCode == 57419) {
if (start > 0) { editText.setSelection(start - 1); }
} else if (primaryCode == 57421) {
if (start < editText.length()) { editText.setSelection(start + 1); }
} else {
edittable.insert(start, Character.toString((char) primaryCode));
}
}
}
在 Activity 中為 EditText 註冊觸摸事件,點擊時彈出自訂鍵盤:
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
private EditText editText1, editText2;
private View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
setContentView(view);
editText1 = (EditText) findViewById(R.id.Etext_1);
editText2 = (EditText) findViewById(R.id.Etext_2);
editText1.setOnTouchListener(this);
editText2.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
editText1.setInputType(InputType.TYPE_NULL);
editText2.setInputType(InputType.TYPE_NULL);
switch (v.getId()) {
case R.id.Etext_1:
new XMlKeysUtils(this, editText1).showKeyBoard();
break;
case R.id.Etext_2:
new XMlKeysUtils(getApplicationContext(), view, editText2).showKeyBoard();
break;
}
return true;
}
return false;
}
}
做到這裡,一個完全自訂的 XML 軟鍵盤就完成開發了。
Android 自定義 View:打造流暢的等待旋轉(ProgressWheel)控件
本文示範如何實作一個可自定義的圓形等待旋轉控件 ProgressWheel,支援 indeterminate 轉圈動畫與 determinate 進度顯示兩種模式,並可透
Android 貪吃蛇:繪製虛擬方向鍵與箭頭
方向鍵的繪製概念 在貪吃蛇小遊戲中,虛擬方向鍵是常見的控制方式。可以使用 Canvas、Path 與 Paint 繪製三角形背景,再搭配箭頭圖形,讓玩家知道目前可操作的區
在 Win10 上架設 Ionic 框架開發 Android 應用的完整環境
在 Win10 上架設 Ionic 框架開發 Android 應用的完整環境 轉載請注明出處:https://www.cnblogs.com/titibili/p/510
PopupWindow 彈窗的完整實現與動畫效果
PopupWindow 是 Android 中常用的浮動彈窗控件,可以實現類似菜單的浮層效果。下圖展示了本文要實現的樣式: 彈窗布局 popup_appinfo.xm