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

深入剖析:Android 監聽輸入法回車鍵與搜尋鍵的完整回呼流程

編輯:關於 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 的按鍵分發

接著看 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 對回車鍵的處理

再往下一層進入 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:真正的分岔口

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;

五、sendDefaultEditorAction 的判定條件

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

實現落在 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 這個欄位。

九、閉環:從 IME 到你的 Callback

回到 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);二是當你想自定義輸入法並讓上層應用感知「搜尋鍵」時,知道該把事件投遞到哪裡。

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