android修改软键盘的回车键为搜索键以及点击时执行两次监听事件的问题

android项目中要实现这样一个需求,在搜索框中输入关键词,在手机弹出的软键盘中,回车键变为搜索键,点击搜索键执行搜索。

1、修改EditText属性:

             

android:imeOption="actionSearch"的作用是将回车两字改为搜索,

android:singleLine="true"的作用是防止搜索框换行。

2、OnKeyListener事件:

        et_search=(EditText)findViewById(R.id.et_search);
        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //是否是回车键
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    //隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //搜索
                    search();
                }
                return false;
            }
        });

做到这一步,前面提到的项目需求基本满足了。


3、点击时执行两次监听事件的问题:

执行上述代码我发现每次点击搜索都会执行两次搜索方法,后来发现时忘了没有加event.getAction() == KeyEvent.ACTION_DOWN这句判断。

修改代码如下:

        et_search=(EditText)findViewById(R.id.et_search);
        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //是否是回车键
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    //隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //搜索
                    search();
                }
                return false;
            }
        });


你可能感兴趣的:(Android)