点击键盘Enter键执行两次事件的解决方案

EditText控件添加属性

android:singleLine="true"

弹出的软盘输入法中回车键为next,直到最后一个获取焦点后显示为Done,点击Done后,软盘输入键盘便隐藏。

etTitle.setOnKeyListener(newView.OnKeyListener() {
    @Override
    public booleanonKey(View v, intkeyCode,KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_ENTER) {
            LogUtil.d(TAG,"initView debug, OnKeyListener, KEYCODE_ENTER");
            InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if(imm.isActive()) {
                imm.hideSoftInputFromWindow(v.getApplicationWindowToken(),0);
            }
            return true;
        }
        return false;
    }
});

APP运行后执行两次Enter事件:

04-17 22:14:43.796 4925-4925/com.. D/com...ui.activities.MainActivity: initView debug, OnKeyListener, KEYCODE_ENTER

04-17 22:14:43.812 4925-4925/com.. D/com...ui.activities.MainActivity: initView debug, OnKeyListener, KEYCODE_ENTER

由于Key有Down和Up事件,所以会执行两次。我们只需监听Down事件即可。

解决方案:

etTitle.setOnKeyListener(newView.OnKeyListener() {
    @Override
    public booleanonKey(View v, intkeyCode,KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)
        *******

输出一次:

04-17 22:25:06.837 19413-19413/com.. D/com...ui.activities.MainActivity: initView debug, OnKeyListener, KEYCODE_ENTER

I Don't Want Your Money, I Want Aragaki Yui.