软键盘的Enter键默认显示的是“完成”文本,我们知道按Enter建表示前置工作已经准备完毕了,要去什么什么啦。比如,在一个搜索中,我们输入要搜索的文本,然后按Enter表示要去搜索了,但是默认的Enter键显示的是“完成”文本,看着不太合适,不符合搜索的语义,如果能显示“搜索”两个字或者显示一个表示搜索的图标多好。
Android也为我们提供的这样的功能。通过设置EditText的android:imeOptions属性来改变默认的“完成”文本。这里举几个常用的常量值:
actionUnspecified 未指定,对应常量EditorInfo.IME_ACTION_UNSPECIFIEDactionNone 没有动作,对应常量EditorInfo.IME_ACTION_NONE
actionGo 去往,对应常量EditorInfo.IME_ACTION_GO
actionSearch 搜索,对应常量EditorInfo.IME_ACTION_SEARCH
actionSend 发送,对应常量EditorInfo.IME_ACTION_SEND
actionNext 下一个,对应常量EditorInfo.IME_ACTION_NEXT
actionDone 完成,对应常量EditorInfo.IME_ACTION_DONE
软键盘Enter键事件处理
捕获EditText软键盘Enter键事件有两种方法:
1)EditText.setOnKeyListener(this);2)EditText.setOnEditorActionListener(this); //用法有所不同
下面通过代码来演示一下具体如何处理
et_search.setOnEditorActionListener(this);
et_search.setOnKeyListener(this);
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_ENTER){
userInput = et_search.getText().toString();
if(TextUtils.isEmpty(userInput)){
LogUtil.e(TAG, "IME_ACTION_SEARCH input is null");
return true;
}
userInput = userInput.trim();
doSearch(userInput);
return true;
}
return false;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
switch (actionId) {
case EditorInfo.IME_ACTION_SEARCH:
case EditorInfo.IME_ACTION_DONE:
case EditorInfo.IME_ACTION_GO:
case EditorInfo.IME_ACTION_NEXT:
case EditorInfo.IME_ACTION_SEND:
userInput = et_search.getText().toString();
if(TextUtils.isEmpty(userInput)){
LogUtil.e(TAG, "IME_ACTION_SEARCH input is null");
return true;
}
userInput = userInput.trim();
doSearch(userInput);
return true;
default:
break;
}
return false;
}
项目中发现第二种方法在某些手机上不起作用如小米2S,所以推荐使用第一种方法来捕获Enter事件。