输入法软键盘搜索执行两次的解决方法
16lz
2021-12-04
要做输入法软键盘搜索其实是挺简单的,在xml布局文件里这样设置编辑框:
android:focusable="true"
android:focusableInTouchMode="true"
这两个属性一定要在编辑框的父布局上,用于屏蔽EditText自动获取焦点问题,然后在EditText上加入
android:imeOptions="actionSearch"
android:singleLine="true"
即可改变软键盘的回车变成搜索按钮或者搜索汉字
但是,搜索的逻辑你可能会这样写:
search_text_view1.setOnEditorActionListener { v, actionId, event -> //修改回车键功能 if (actionId === EditorInfo.IME_ACTION_SEARCH || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)) { // 隐藏键盘 (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(this@GoodsSelecotorActivity.currentFocus .windowToken, InputMethodManager.HIDE_NOT_ALWAYS) keywords = search_text_view1.text.toString() currentPage = 1 getRequestData(promotionId) } false }
或者
search_text_view1.setOnKeyListener { v, actionId, event -> //修改回车键功能 if (actionId === EditorInfo.IME_ACTION_SEARCH || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)) { // 隐藏键盘 (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(this@GoodsSelecotorActivity.currentFocus .windowToken, InputMethodManager.HIDE_NOT_ALWAYS) keywords = search_text_view1.text.toString() currentPage = 1 getRequestData(promotionId) } false }
那么恭喜你,你已经掉坑了:搜索方法会执行两次
其实,当你调用setOnKeyListener的时候已经进坑了,这个方法是会执行两次的,就会导致你的网络请求执行两次,那么要么是加载弹窗一直显示,要么是数据重复了,正确的做法是放弃该方法,调用setOnEditorActionListener ,但是这个里面也要做一些修改才行,
search_text_view1.setOnEditorActionListener { v, actionId, event -> //修改回车键功能 if (actionId === EditorInfo.IME_ACTION_SEARCH) { // 隐藏键盘 (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(this@GoodsSelecotorActivity.currentFocus .windowToken, InputMethodManager.HIDE_NOT_ALWAYS) keywords = search_text_view1.text.toString() currentPage = 1 getRequestData(promotionId) } false }
对,就是这样,if判断力精简了
if (actionId === EditorInfo.IME_ACTION_SEARCH) {
//正常逻辑
}
有的时候,加的判断多了,反而适得其反,Ok,就这样了。
更多相关文章
- Android(安卓)Framework中JNI调用
- Android(安卓)ApiDemos示例解析(15):App->Activity->SetWallpaper
- 【Flutter】修改图标、应用名称、包名等
- 软键盘显示及属性android:windowSoftInputMode使用总结 & [转一
- Android(安卓)隐藏/显示 Actionbar之后不能运行的问题
- 基于Android(安卓)studio3.6的JNI教程之helloworld思路详解
- Android(安卓)Eclipse插件TabHost问题(转载)
- Android知识点——更改软键盘回车键
- android:windowSoftInputMode属性使用