EditText 中google原生态键盘del键无法响应onkeyListener事件

EditText 中google原生态键盘del键无法响应onkeyListener事件

转载:
CSDN: EditText 中google原生态键盘del键无法响应onkeyListener事件
StackOverFlow: Android EditText delete(backspace) key event

Android原生软键盘不响应onKeyListener。

解决此问题通过重写EditText中'InputConnection'类的sendKeyEvent方法来实现,下面是实现代码。

public class SecurityEditText extends EditText {  
  
    private OnDelKeyEventListener delKeyEventListener;  
  
    public SecurityEditText(Context context) {  
        super(context);  
    }  
  
    public SecurityEditText(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
  
    public SecurityEditText(Context context, AttributeSet attrs, int defStyle) {  
        super(context, attrs, defStyle);  
    }  
  
    @Override  
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {  
        return new ZanyInputConnection(super.onCreateInputConnection(outAttrs),  
                true);  
    }  
  
    private class ZanyInputConnection extends InputConnectionWrapper {  
  
        public ZanyInputConnection(InputConnection target, boolean mutable) {  
            super(target, mutable);  
        }  
  
        @Override  
        public boolean sendKeyEvent(KeyEvent event) {  
            if (event.getAction() == KeyEvent.ACTION_DOWN  
                    && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {  
                if (delKeyEventListener != null) {  
                    delKeyEventListener.onDeleteClick();  
                    return true;  
                }  
            }  
            return super.sendKeyEvent(event);  
        }  
  
        @Override  
        public boolean deleteSurroundingText(int beforeLength, int afterLength) {  
            if (beforeLength == 1 && afterLength == 0) {  
                return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,  
                        KeyEvent.KEYCODE_DEL))  
                        && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,  
                                KeyEvent.KEYCODE_DEL));  
            }  
  
            return super.deleteSurroundingText(beforeLength, afterLength);  
        }  
    }  
  
    /** 
     *  
     * 功能描述: 
* 〈功能详细描述〉 * * @param delKeyEventListener EditText删除回调 */ public void setDelKeyEventListener(OnDelKeyEventListener delKeyEventListener) { this.delKeyEventListener = delKeyEventListener; } public interface OnDelKeyEventListener { void onDeleteClick(); } }

你可能感兴趣的:(EditText 中google原生态键盘del键无法响应onkeyListener事件)