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

Android 自訂純數字軟鍵盤實作教學

編輯:關於 Android 開發

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>

二、定義鍵盤按鍵(hexkbd.xml)

在 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>

三、Activity 中的使用

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;
        }
    }
}

四、核心類 CustomKeyboard

這個類封裝了自訂鍵盤的全部邏輯,包括鍵盤的顯示/隱藏、按鍵事件的處理,以及禁用系統輸入法的關鍵操作:

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 來禁用系統輸入法。掌握這幾點後,就能靈活打造各種符合業務需求的自訂輸入元件。

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