1. 程式人生 > >EditText 中google原生態鍵盤del鍵無法響應onkeyListener事件

EditText 中google原生態鍵盤del鍵無法響應onkeyListener事件

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);
        }
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能詳細描述〉
     *
     * @param delKeyEventListener EditText刪除回撥
     */
    public void setDelKeyEventListener(OnDelKeyEventListener delKeyEventListener) {
        this.delKeyEventListener = delKeyEventListener;
    }

    public interface OnDelKeyEventListener {
        void onDeleteClick();
    }

}

結合我的這篇http://blog.csdn.net/yaya_soft/article/details/44307847  O(∩_∩)O哈哈~完美了