編輯:關於 Android 程式設計
很多開發者都遇到過這樣的困惑:自定義輸入法(IME)明明按下了回車鍵,為什麼 App 裡的 OnEditorActionListener 卻沒有觸發?要回答這個問題,得把整条鏈路從 InputMethodService 一路跟到 TextView。下面我們就順著源碼走一遍。
在繼承 InputMethodService 的服務裡,我們先取得按鍵碼,再手工構造一對按下/抬起事件:
int keyCode = sKey.getKeyCode();
KeyEvent eDown = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, keyCode, 0, 0, 0, 0, KeyEvent.FLAG_SOFT_KEYBOARD); KeyEvent eUp = new KeyEvent(0, 0, KeyEvent.ACTION_UP, keyCode, 0, 0, 0, 0, KeyEvent.FLAG_SOFT_KEYBOARD); onKeyDown(keyCode, eDown); onKeyUp(keyCode, eUp);
關鍵就在這裡:只要呼叫 onKeyDown / onKeyUp,按鍵事件就被下發給了當前連接的應用,於是應用側的按鍵監聽邏輯才有機會被觸發。
接著看 InputMethodService 自己對這兩個回呼的處理:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (processKey(event, 0 != event.getRepeatCount())) return true;
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (processKey(event, true)) return true;
return super.onKeyUp(keyCode, event);
}
打點跟蹤可以發現,焦點應該放在 onKeyUp 上,它直接在這一行返回了 true:
if (processKey(event, true)) return true;
走進 processKey 之後,真正起作用的是它內部對功能鍵的判斷:
if (processFunctionKeys(keyCode, realAction)) {
return true;
}
再往下一層進入 processFunctionKeys,可以看到針對 KEYCODE_ENTER 的專門分支:
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (!realAction){
Log.d(TAG, "processFunctionKeys call KEYCODE_ENTER return");
return true;
}
sendKeyChar('\n');
return true;
}
由於外層傳入的 realAction 為 true(抬起事件),所以程式實際執行的是:
sendKeyChar('\n');
sendKeyChar 定義在 InputMethodService 中:
public void sendKeyChar(char charCode) {
switch (charCode) {
case '\n':
// Apps may be listening to an enter key to perform an action
if (!sendDefaultEditorAction(true)) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_ENTER);
}
break;
default:
// Make sure that digits go through any text watcher on the client side.
if (charCode >= '0' && charCode <= '9') {
sendDownUpKeyEvents(charCode - '0' + KeyEvent.KEYCODE_0);
} else {
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.commitText(String.valueOf((char) charCode), 1);
}
}
break;
}
}
因為傳進來的是 '\n',所以走的是第一個分支。注意原始碼裡那行註釋——Apps may be listening to an enter key to perform an action——它把意圖說得非常直白:應用可能正在等著回車鍵來執行某個動作。
case '\n':
// Apps may be listening to an enter key to perform an action
if (!sendDefaultEditorAction(true)) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_ENTER);
}
break;
public boolean sendDefaultEditorAction(boolean fromEnterKey) {
EditorInfo ei = getCurrentInputEditorInfo();
if (ei != null
&& (!fromEnterKey || (ei.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) == 0)
&& (ei.imeOptions & EditorInfo.IME_MASK_ACTION) != EditorInfo.IME_ACTION_NONE) {
// If the enter key was pressed, and the editor has a default
// action associated with pressing enter, then send it that
// explicit action instead of the key event.
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.performEditorAction(ei.imeOptions & EditorInfo.IME_MASK_ACTION);
}
return true;
}
return false;
}
這個方法本質上只是一句「通知」:告訴編輯器執行它自己聲明過的動作。
/** * Have the editor perform an action it has said it can do. */ public boolean performEditorAction(int editorAction);
/**
* Set of bits in {@link #imeOptions} that provide alternative actions
* associated with the "enter" key. This both helps the IME provide
* better feedback about what the enter key will do, and also allows it
* to provide alternative mechanisms for providing that command.
*/
public static final int IME_MASK_ACTION = 0x000000ff;
實現落在 EditableInputConnection 中(關於為何是它,可參考前文對 InputConnection Selection 的說明):
@Override
public boolean performEditorAction(int actionCode) {
if (DEBUG) Log.v(TAG, "performEditorAction " + actionCode);
mTextView.onEditorAction(actionCode);
return true;
}
所以普通應用想攔截「GO」「搜尋」「完成」這類鍵盤動作鍵,標準寫法如下:
edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
/*判斷是否是「GO」鍵*/
if (actionId == EditorInfo.IME_ACTION_GO) {
edittext.setText("success");
return true;
}
return false;
}
});
這裡用到的是 TextView 內部定義的監聽介面:
/**
* Interface definition for a callback to be invoked when an action is
* performed on the editor.
*/
public interface OnEditorActionListener {
/**
* Called when an action is being performed.
*
* @param v The view that was clicked.
* @param actionId Identifier of the action. This will be either the
* identifier you supplied, or {@link EditorInfo#IME_NULL
* EditorInfo.IME_NULL} if being called due to the enter key
* being pressed.
* @param event If triggered by an enter key, this is the event;
* otherwise, this is null.
* @return Return true if you have consumed the action, else false.
*/
boolean onEditorAction(TextView v, int actionId, KeyEvent event);
}
/**
* Set a special listener to be called when an action is performed
* on the text view. This will be called when the enter key is pressed,
* or when an action supplied to the IME is selected by the user.
*/
public void setOnEditorActionListener(OnEditorActionListener l) {
if (mInputContentType == null) {
mInputContentType = new InputContentType();
}
mInputContentType.onEditorActionListener = l;
}
可以看到,我們傳入的 l 被存進了 mInputContentType.onEditorActionListener 這個欄位。
回到 EditableInputConnection.performEditorAction,它呼叫的 mTextView.onEditorAction(actionCode) 是這樣實現的:
public void onEditorAction(int actionCode) {
final InputContentType ict = mInputContentType;
if (ict != null) {
if (ict.onEditorActionListener != null) {
if (ict.onEditorActionListener.onEditorAction(this, actionCode, null)) {
return;
}
}
}
}
至此整条鏈路完全打通:
IME 收到實體/軟鍵盤的回車 → onKeyUp → processKey → processFunctionKeys → sendKeyChar('\n') → sendDefaultEditorAction → InputConnection.performEditorAction → TextView.onEditorAction → 你注册的 OnEditorActionListener。
理解這條鏈路有兩個實用價值:一是當回呼不觸發時,你能準確定位是哪一環斷了(最常見的是 imeOptions 沒設成非 IME_ACTION_NONE,或者設了 IME_FLAG_NO_ENTER_ACTION);二是當你想自定義輸入法並讓上層應用感知「搜尋鍵」時,知道該把事件投遞到哪裡。
SEAndroid 介紹及其基本原理
1. 什麼是 SEAndroid SEAndroid(Security-Enhanced Android)是由美國國家安全局(NSA)開發的開源安全專案,在 Google
百度有錢花怎麼分期還款 三大場景詳細說明
百度有錢花是百度金融旗下的消費金融品牌,定位為面向大眾的個人消費金融權益平台,主打創新型消費信貸模式。目前它已在多個產業展開探索與佈局,其中教育信貸業務開通了遠程異地預授
Android GPS 應用程式設計完整指南
GPS 簡介 GPS 是英文 Global Positioning System(全球定位系統)的簡稱,是 20 世紀 70 年代由美國陸海空三軍聯合研制的新一代空間衛星
Android 中使用 SQLite 數據庫的完整實踐
SQLite 憑藉輕量、體積小等優勢,在移動開發中被廣泛使用。此前我介紹過如何在 Cocos2d-x 中使用 SQLite,本文則聚焦於 Android 平台。由於 An