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

http://blog.csdn.net/coderK2014/article/details/51766485

1、修改EditText属性:

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <EditText  
  2.    android:id="@+id/et_search"  
  3.    android:layout_width="100dp"  
  4.    android:layout_height="25dp"  
  5.    android:textSize="12sp"  
  6.    android:hint="请输入关键词"  
  7.    android:imeOptions="actionSearch"  
  8.    android:singleLine="true"/>  

 

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

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

2、OnKeyListener事件:

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. et_search=(EditText)findViewById(R.id.et_search);  
  2. et_search.setOnKeyListener(new View.OnKeyListener() {  
  3.     @Override  
  4.     public boolean onKey(View v, int keyCode, KeyEvent event) {  
  5.         //是否是回车键  
  6.         if (keyCode == KeyEvent.KEYCODE_ENTER) {  
  7.             //隐藏键盘  
  8.             ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))  
  9.                     .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()  
  10.                             .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);  
  11.             //搜索  
  12.             search();  
  13.         }  
  14.         return false;  
  15.     }  
  16. });  


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

 

 

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

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

修改代码如下:

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. et_search=(EditText)findViewById(R.id.et_search);  
  2. et_search.setOnKeyListener(new View.OnKeyListener() {  
  3.     @Override  
  4.     public boolean onKey(View v, int keyCode, KeyEvent event) {  
  5.         //是否是回车键  
  6.         if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {  
  7.             //隐藏键盘  
  8.             ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))  
  9.                     .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()  
  10.                             .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);  
  11.             //搜索  
  12.             search();  
  13.         }  
  14.         return false;  
  15.     }  
  16. });  

 

posted on 2016-07-17 12:53  oyl  阅读(233)  评论(0)    收藏  举报

导航