您的位置:首页 > 其它

在Activity/Fragment中设置搜索键的监听事件

2016-09-02 11:48 253 查看
猴子每天都要经历九九八十一难,种种bug迎风吹来。

首先设置TextView的两个属性:

(1)android:imeOptions="actionSearch"

(2)android:singleLine="true"(高版本会提示过时)或android:lines="1"

温馨提示少了第二个属性,软键盘永远不会将回车键修改为带“搜索”两字的按钮,就无法实现功能了

1、Activity中:

etSearch.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH){
// 先隐藏键盘
((InputMethodManager) etSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
Log.e("可以实现吗", "is ok ?");
return true;
}
return false;
}
});

2、Fragment中,其实就是注意一下就可以了(this\context\getactivity...):

editSearch.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH){
// 先隐藏键盘
((InputMethodManager) editSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
//获取编辑框内容,执行相应操作

return true;
}
return false;
}
});


3、网上说会执行两次的原因及解决:

etSearch.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
/**
* 看情况是否需要满足其一条件
* (keyCode == KeyEvent.KEYCODE_SEARCH) || (keyCode == KeyEvent.KEYCODE_ENTER)
*
* 如果少了event.getAction() == KeyEvent.ACTION_DOWN则会执行两次
* */
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
//满足条件则隐藏软键盘
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// TODO: 2016/9/2 具体根据按搜索键后执行的操作
Log.e("will do twice ?", "I can't believe 1");
}
return false;
}
});


对于网上说不是setOnKey...而是上面匿名方法(setOnEditorActionListener),暂时没时间去研究
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐