setOnKeyListener不可靠,硬鍵盤可靠,軟鍵盤不可靠
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.
當(dāng)硬件鍵事件被分派到此視圖時,要調(diào)用的回調(diào)的接口定義。
回調(diào)函數(shù)將在鍵事件被賦予視圖之前被調(diào)用。
這只對硬件鍵盤有用;
軟件輸入法沒有義務(wù)觸發(fā)這個監(jiān)聽器。
使用InputConnection,重寫onCreateInputConnection放在,在commitText方法里,監(jiān)聽按鍵
public class TEditText extends AppCompatEditText {
public TEditText(Context context) {
super(context);
}
public TEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 當(dāng)輸入法和EditText建立連接的時候會通過這個方法返回一個InputConnection。
* 我們需要代理這個方法的父類方法生成的InputConnection并返回我們自己的代理類。
*/
@Override
public InputConnection onCreateInputConnection(EditorInfo editorInfo) {
return new InputConnectionWrapper(super.onCreateInputConnection(editorInfo),false) {
public boolean commitText(CharSequence text, int newCursorPosition) {
if (text.equals("@")) {
}
return super.commitText(text, newCursorPosition);
}
};
}
}