OnKeyListener 和 OnEditorActionListener 之间的确切区别是什么?

Mar*_*rat 7 keyboard android android-edittext

我读过它OnKeyListener用于检测硬键和OnEditorActionListener软键。但是,互联网上有很多示例,因此它们似乎在任何情况下都可以正常工作。

我曾经尝试都和OnKeyListener工作只有真实设备,同时OnEditorActionListener对工程实际设备和仿真器了。

因此,我想知道它们之间的区别并弄清楚何时使用它们中的任何一个。如果有人能解释我,我将不胜感激。

Eri*_* B. 5

只是从文档中复制粘贴:

 /**
     * Interface definition for a callback to be invoked when a hardware key event is
     * dispatched to this view. The callback will be invoked before the key event is
     * given to the view. This is only useful for hardware keyboards; a software input
     * method has no obligation to trigger this listener.
     */
    public interface OnKeyListener {
        /**
         * Called when a hardware key is dispatched to a view. This allows listeners to
         * get a chance to respond before the target view.
         * <p>Key presses in software keyboards will generally NOT trigger this method,
         * although some may elect to do so in some situations. Do not assume a
         * software input method has to be key-based; even if it is, it may use key presses
         * in a different way than you expect, so there is no way to reliably catch soft
         * input key presses.
         *
         * @param v The view the key has been dispatched to.
         * @param keyCode The code for the physical key that was pressed
         * @param event The KeyEvent object containing full information about
         *        the event.
         * @return True if the listener has consumed the event, false otherwise.
         */
        boolean onKey(View v, int keyCode, KeyEvent event);
    }
Run Code Online (Sandbox Code Playgroud)

不要假设软件输入法必须是基于键的;即使是这样,它也可能以与您预期不同的方式使用按键,因此无法可靠地捕获软输入按键。

相似地,

   /**
     * 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.  Setting
     * this means that the normal hard key event will not insert a newline
     * into the text view, even if it is multi-line; holding down the ALT
     * modifier will, however, allow the user to insert a newline character.
     */
    public void setOnEditorActionListener(OnEditorActionListener l) {
        createEditorIfNeeded();
        mEditor.createInputContentTypeIfNeeded();
        mEditor.mInputContentType.onEditorActionListener = l;
    }
Run Code Online (Sandbox Code Playgroud)

  • 那么,这意味着 `OnEditorActionListener` 优于 `OnKeyListener` 吗?因为,在某些情况下,最后一个可能不会被触发? (2认同)