Android的EditText通过setOnEditorActionListener给文本编辑框设置监听事件,但是在其处理方法onEditorAction中的逻辑在每次回车后都触发了两次,原来是在键盘回车的ACTION_UP和ACTION_DOWN时都会触发这个方法,因此修改代码如下,就防止了两次执行:
1 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 2 //以下方法防止两次发送请求 3 if (actionId == EditorInfo.IME_ACTION_SEND || 4 (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) { 5 switch (event.getAction()) { 6 case KeyEvent.ACTION_UP: 7 //发送请求 8 String keyWord = et_search.getText().toString().trim(); 9 if (null == keyWord) 10 keyWord = ""; 11 dismisspopup(); 12 LogUtils.d("向服务器发送搜索请求:" + keyWord); 13 //发起查询 14 searchByKeyWord(keyWord); 15 hideSoftInput(); 16 return true; 17 default: 18 return true; 19 } 20 } 21 return false; 22 }