編輯:關於 Android 程式設計
本文為大家分享一個自定義輸入法的實現示例,供感興趣的讀者參考。
對於Android用戶來說,大多數人都習慣使用第三方輸入法。然而在輸入密碼(尤其是支付相關的密碼)時,第三方輸入法存在極大的安全隱患。目前很多網銀類App和支付軟件在用戶輸入密碼時,都會彈出自定義的輸入法,而不是直接調用系統輸入法。
本文要介紹的,正是如何實現一個簡單的自定義輸入法。當然,你也可以寫一個Dialog擺上幾十個按鈕來接收輸入,只是那樣顯得不太專業。
(一)先看效果圖:
1.前兩個輸入框使用了自定義輸入法:

2.第三個輸入框未做任何設置,因此使用默認的系統輸入法:

(二)代碼解析:
1.主頁面布局由3個輸入框和一個android.inputmethodservice.KeyboardView組成。KeyboardView是系統自帶、繼承自View的組件,但它不在android.view包下,因此引用時要寫上完整的包名。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!--前兩個EditText均使用自定義的輸入法--> <EditText android:id="@+id/input_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:hint="one password" android:layout_alignParentTop="true" android:inputType="textPassword" /> <EditText android:id="@+id/input_password2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/input_password" android:layout_margin="8dp" android:hint="another password" android:inputType="textPassword" /> <!--這個EditText使用默認的輸入法--> <EditText android:id="@+id/input_normal_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/input_password2" android:layout_margin="8dp" android:hint="normal text" /> <android.inputmethodservice.KeyboardView android:id="@+id/keyboardview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:focusable="true" android:focusableInTouchMode="true" android:visibility="gone" /> </RelativeLayout>
2.KeyboardView只是一個顯示輸入法的容器控件,使用時需要為它設置具體的鍵盤面板內容。
(1)首先在res下新建xml目錄,並在其中創建keys_layout.xml,用來定義輸入法面板。每個row代表一行,Keyboard的keyWidth和keyHeight屬性表示按鍵大小,25%p表示佔父組件的25%;Key的codes屬性表示按鍵編號(點擊時回調方法會返回這個值,用於區分不同按鍵),keyLabel則是按鍵上顯示的文字。還有許多其他屬性,這裡不再贅述。
<?xml version="1.0" encoding="utf-8"?> <Keyboard xmlns:android="https://schemas.android.com/apk/res/android" android:keyWidth="25%p" android:keyHeight="10%p"> <Row> <Key android:codes="55" android:keyLabel="7" android:keyEdgeFlags="left" /> <Key android:codes="56" android:keyLabel="8" /> <Key android:codes="57" android:keyLabel="9" /> <!--刪除按鍵長按時連續響應--> <Key android:codes="60001" android:keyLabel="DEL" android:isRepeatable="true" /> </Row> <Row> <Key android:codes="52" android:keyLabel="4" android:keyEdgeFlags="left" /> <Key android:codes="53" android:keyLabel="5" /> <Key android:codes="54" android:keyLabel="6" /> <Key android:codes="48" android:keyLabel="0" /> </Row> <Row> <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left" /> <Key android:codes="50" android:keyLabel="2" /> <Key android:codes="51" android:keyLabel="3" /> <Key android:codes="60002" android:keyLabel="Cancel" /> </Row> </Keyboard>
(2)為了使用方便,新建一個KeyboardBuilder.java類,用於初始化自定義輸入法並綁定EditText,代碼如下:
public class KeyboardBuilder { private static final String TAG = "KeyboardBuilder"; private Activity mActivity; private KeyboardView mKeyboardView; public KeyboardBuilder(Activity ac, KeyboardView keyboardView, int keyBoardXmlResId) { mActivity = ac; mKeyboardView = keyboardView; Keyboard mKeyboard = new Keyboard(mActivity, keyBoardXmlResId); // Attach the keyboard to the view mKeyboardView.setKeyboard(mKeyboard); // Do not show the preview balloons mKeyboardView.setPreviewEnabled(false); KeyboardView.OnKeyboardActionListener keyboardListener = new KeyboardView.OnKeyboardActionListener() { @Override public void onKey(int primaryCode, int[] keyCodes) { // Get the EditText and its Editable View focusCurrent = mActivity.getWindow().getCurrentFocus(); if (focusCurrent == null || !(focusCurrent instanceof EditText)) { return; } EditText edittext = (EditText) focusCurrent; Editable editable = edittext.getText(); int start = edittext.getSelectionStart(); // Handle key if (primaryCode == Constant.CodeCancel) { hideCustomKeyboard(); } else if (primaryCode == Constant.CodeDelete) { if (editable != null && start > 0) { editable.delete(start - 1, start); } } else { // Insert character 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() { } }; mKeyboardView.setOnKeyboardActionListener(keyboardListener); } //綁定一個EditText public void registerEditText(EditText editText) { // Make the custom keyboard appear editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { showCustomKeyboard(v); } else { hideCustomKeyboard(); } } }); editText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick"); showCustomKeyboard(v); } }); editText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d(TAG, "onTouch"); EditText edittext = (EditText) v; int inType = edittext.getInputType(); // Backup the input type edittext.setInputType(InputType.TYPE_NULL); // Disable standard keyboard edittext.onTouchEvent(event); // Call native handler edittext.setInputType(inType); // Restore input type edittext.setSelection(edittext.getText().length()); return true; } }); } public void hideCustomKeyboard() { mKeyboardView.setVisibility(View.GONE); mKeyboardView.setEnabled(false); } public void showCustomKeyboard(View v) { mKeyboardView.setVisibility(View.VISIBLE); mKeyboardView.setEnabled(true); if (v != null) { ((InputMethodManager) mActivity.getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0); } } public boolean isCustomKeyboardVisible() { return mKeyboardView.getVisibility() == View.VISIBLE; } }
3.最後是主Activity的代碼,這部分就很簡單了。
/** * 自定義安全輸入法 */ public class MainActivity extends ActionBarActivity { private KeyboardBuilder builder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); KeyboardView keyboardView = (KeyboardView) findViewById(R.id.keyboardview); builder = new KeyboardBuilder(this, keyboardView, R.xml.keys_layout); EditText editText = (EditText) findViewById(R.id.input_password); builder.registerEditText(editText); EditText editText2 = (EditText) findViewById(R.id.input_password2); builder.registerEditText(editText2); } @Override public void onBackPressed() { if (builder != null && builder.isCustomKeyboardVisible()) { builder.hideCustomKeyboard(); } else { this.finish(); } } }
更多Android相關內容感興趣的讀者可查看本站專題:《Android視圖View技巧總結》、《Android開發動畫技巧匯總》、《Android編程之activity操作技巧總結》、《Android布局layout技巧總結》、《Android開發入門與進階教程》、《Android資源操作技巧匯總》及《Android控件用法總結》。
希望本文所述對大家Android程序設計有所幫助。
WebView 中介紹 JavaScript 與 Java 雙向調用的完整實踐
混合開發中經常需要網頁調用原生能力,比如拍照、選相冊、錄音。Android 的 WebView 基於 WebKit 內核,內建了 JS 與 Java 互調的接口,接入並不
ListView 分頁加載實戰:把加載更多的監聽放在 FooterView 裡
ListView 是 Android 最常用的控件之一。實戰中經常遇到一次性加載全部數據過多、影響性能的情況,這時就需要分頁加載。 本示例把「加載更多」的觸發點放在 Li
Android 常用號碼功能實作:SQLite 搭配 ExpandableListView
不少 Android 手機都內建了常用號碼功能,例如訂餐電話、公共服務電話、航空機票等分類,點一下對應號碼就會跳出撥號介面。本文就來實作一個類似的小範例。 一、實作原理
自訂 ListView 頂部與底部箭頭指示器的實作教學
本文要做的效果,是在 ListView 上下加一對箭頭:捲到頂端時上方箭頭消失,往下捲動(上面有內容被遮住)時才出現;底部同理。系統預設的 ListView / Scro