編輯:關於 Android 開發
在某些場景下(例如計算器、驗證碼輸入、金額輸入),我們希望使用一個只包含數字與少量符號的自訂軟鍵盤,而非系統預設的輸入法。本文將透過一個完整的範例,示範如何打造一個純數字自訂鍵盤。
首先在 Activity 佈局中放置一個 EditText 與一個 KeyboardView,其中 KeyboardView 初期設為隱藏:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginRight="24dp"
android:ems="10"
android:inputType="none" >
<requestFocus />
</EditText>
<android.inputmethodservice.KeyboardView
android:id="@+id/keyboardview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="5.0dp"
android:background="#ffffffff"
android:focusable="true"
android:keyBackground="@drawable/calculator_button_bg"
android:keyTextColor="@color/black"
android:keyTextSize="26.0sp"
android:shadowColor="#ffffffff"
android:shadowRadius="0.0"
android:visibility="gone" />
</RelativeLayout>
在 res/xml 目錄下建立鍵盤佈局檔,用 Row 與 Key 描述每一排按鍵。每個 Key 的 android:codes 對應其 ASCII 碼(如 '7' 為 55),-5 則代表刪除鍵:
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="https://schemas.android.com/apk/res/android"
android:background="#ffffffff"
android:keyHeight="10%p"
android:keyWidth="100%p" >
<Row>
<Key android:codes="55" android:keyEdgeFlags="left" android:keyLabel="7" />
<Key android:codes="56" android:keyLabel="8" />
<Key android:codes="57" android:keyLabel="9" />
</Row>
<Row>
<Key android:codes="52" android:keyEdgeFlags="left" android:keyLabel="4" />
<Key android:codes="53" android:keyLabel="5" />
<Key android:codes="54" android:keyLabel="6" />
</Row>
<Row>
<Key android:codes="49" android:keyEdgeFlags="left" android:keyLabel="1" />
<Key android:codes="50" android:keyLabel="2" />
<Key android:codes="51" android:keyLabel="3" />
</Row>
<Row>
<Key android:codes="46" android:keyEdgeFlags="left" android:keyLabel="." />
<Key android:codes="48" android:keyLabel="0" />
<Key android:codes="-5" android:isRepeatable="true"
android:keyIcon="@drawable/sym_keyboard_delete" />
</Row>
</Keyboard>
MainActivity 只需建立 CustomKeyboard 物件並註冊需要用到的 EditText 即可:
package com.example.yanlei.yl2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
CustomKeyboard mCustomKeyboard;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
mCustomKeyboard = new CustomKeyboard(this, R.id.keyboardview, R.xml.hexkbd);
mCustomKeyboard.registerEditText(R.id.editText1);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default: break;
}
}
}
這個類封裝了自訂鍵盤的全部邏輯,包括鍵盤的顯示/隱藏、按鍵事件的處理,以及禁用系統輸入法的關鍵操作:
package com.example.yanlei.yl2;
import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* 當 Activity 承載一個 KeyboardView 時,本類允許多個 EditText 註冊使用它。
*/
class CustomKeyboard {
private KeyboardView mKeyboardView;
private Activity mHostActivity;
/** 按鍵(鍵碼)事件處理器 */
private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
public final static int CodeDelete = -5; // Keyboard.KEYCODE_DELETE
public final static int CodeCancel = -3; // Keyboard.KEYCODE_CANCEL
@Override
public void onKey(int primaryCode, int[] keyCodes) {
// 取得當前焦點的 EditText 及其 Editable
View focusCurrent = mHostActivity.getWindow().getCurrentFocus();
if (focusCurrent == null || focusCurrent.getClass() != EditText.class) return;
EditText edittext = (EditText) focusCurrent;
Editable editable = edittext.getText();
int start = edittext.getSelectionStart();
// 將按鍵作用於 edittext
if (primaryCode == CodeCancel) {
hideCustomKeyboard();
} else if (primaryCode == CodeDelete) {
if (editable != null && start > 0) editable.delete(start - 1, start);
} else {
editable.insert(start, Character.toString((char) primaryCode));
}
}
@Override public void onPress(int arg0) {}
@Override public void onRelease(int primaryCode) {}
@Override public void onText(CharSequence text) {}
@Override public void swipeDown() {}
@Override public void swipeLeft() {}
@Override public void swipeRight() {}
@Override public void swipeUp() {}
};
public CustomKeyboard(Activity host, int viewid, int layoutid) {
mHostActivity = host;
mKeyboardView = (KeyboardView) mHostActivity.findViewById(viewid);
mKeyboardView.setKeyboard(new Keyboard(mHostActivity, layoutid));
mKeyboardView.setPreviewEnabled(false);// 不顯示按鍵預覽氣泡
mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
// 初始時隱藏系統鍵盤
mHostActivity.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public boolean isCustomKeyboardVisible() {
return mKeyboardView.getVisibility() == View.VISIBLE;
}
public void showCustomKeyboard(View v) {
mKeyboardView.setVisibility(View.VISIBLE);
mKeyboardView.setEnabled(true);
if (v != null) ((InputMethodManager) mHostActivity
.getSystemService(Activity.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
public void hideCustomKeyboard() {
mKeyboardView.setVisibility(View.GONE);
mKeyboardView.setEnabled(false);
}
/** 註冊 EditText 以使用本自訂鍵盤 */
public void registerEditText(int resid) {
EditText edittext = (EditText) mHostActivity.findViewById(resid);
// 獲得焦點時顯示自訂鍵盤,失去焦點時隱藏
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) showCustomKeyboard(v);
else hideCustomKeyboard();
}
});
// 再次點擊已獲得焦點的 edittext 時也能重新彈出鍵盤
edittext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showCustomKeyboard(v);
}
});
// 以較底層的方式禁用系統鍵盤
edittext.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
EditText edittext = (EditText) v;
int inType = edittext.getInputType();
edittext.setInputType(InputType.TYPE_NULL);// 禁用系統鍵盤
edittext.onTouchEvent(event);// 呼叫原生處理器
edittext.setInputType(inType);// 還原輸入類型
return true;
}
});
// 禁用拼寫檢查(十六進位字串會被 Android 誤判為單詞)
edittext.setInputType(edittext.getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}
}
總結一下,自訂純數字鍵盤的關鍵點有三個:一是用 XML 定義鍵盤按鍵佈局;二是透過 OnKeyboardActionListener 攔截按鍵並手動操作 Editable;三是透過 setOnTouchListener 動態切換 InputType 來禁用系統輸入法。掌握這幾點後,就能靈活打造各種符合業務需求的自訂輸入元件。
Android Material Design 支援庫完整指南:核心元件與實作重點
Android Material Design 支援庫使用指南 Design Support Library 是 Google 為了讓開發者能在舊版 Android 系統
SpannableString 實作:讓 TextView 裡的某幾個字可以點擊
核心概念 Android 中各種文字樣式(Span)都是透過 SpannableString 來封裝的。流程固定為三步:建立 Span → 把 Span 放進 Spann
天氣 App 布局練習(三):LinearLayout 與 layout_weight
天氣 App 布局練習 本練習重點在於使用 LinearLayout 與 layout_weight 完成天氣首頁的垂直與水平排列。 畫面可拆分為頂部城市與天氣資訊、中
自定義設置密碼對話框實作
自定義設置密碼對話框 在 Android 中,若預設對話框無法滿足需求,可以透過自定義版面配置建立更合適的互動樣式。以下以「設置密碼」為例,說明如何完成一個包含標題、密