zz android修改软键盘的回车键为搜索键以及点击时执行两次监听事件的问题
http://blog.csdn.net/coderK2014/article/details/51766485
1、修改EditText属性:
- <EditText
- android:id="@+id/et_search"
- android:layout_width="100dp"
- android:layout_height="25dp"
- android:textSize="12sp"
- android:hint="请输入关键词"
- android:imeOptions="actionSearch"
- android:singleLine="true"/>
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;
- }
- });

浙公网安备 33010602011771号