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