我已经读过OnKeyListener
用于检测硬键,而OnEditorActionListener
用于检测软键。但是,互联网上有很多示例,因此似乎它们在任何情况下都可以正常工作。
我都尝试过,并且OnKeyListener
仅在真实设备上可以使用,而OnEditorActionListener
也可以在真实设备和模拟器上使用。
因此,我想知道它们之间的区别,并弄清楚何时使用它们中的任何一个。如果有人能解释我,我将不胜感激。
最佳答案
只是从文档中粘贴一小份副本:
/**
* 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);
}
相似地,
/**
* 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;
}