最近做有关模糊搜索的模块,需要实现的功能:
1. 点击搜索框输入内容 ->
2. 点击搜索->
3. 搜索到内容后键盘收起
关键代码:
EditText 中设置:
android:inputType="text"
android:imeOptions="actionSearch"
遇到的问题:
输入完毕,点击软键盘搜索,键盘并未收起,而且键盘可能会变为英文模式,Search键变成回车!
分析问题:
直接在xml中设置actionSearch,只能保证软键盘弹出时的imeOptions模式是搜索模式,带搜索按钮
- imeOptions=”actionSearch” –> EditorInfo.IME_ACTION_SEARCH
但是当确认搜索后 软键盘并不会自动隐藏。
解决问题:
1.设置保证当符合点击搜索条件时,判断当前的action是否为搜索自动隐藏键盘,需要添加setOnEditorActionListener()方法:
edtInput.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) { //搜索按键action 这里与imeOptions相对应
doQuery()
}
false //返回true 保留软键盘 false 直接隐藏
}
注意最后一行,返回false直接隐藏键盘。
也可以设置onFocuse监听:
expire_warning_fragment_like.onFocusChange { v, hasFocus ->
setShowSoftInput(v,hasFocus)
}
2.但是更合理的做法是:返回true,当搜索请求成功返回数据后,再调用主动隐藏键盘的操作:
fun hideKeyforard(view:View) {
val inputMethodManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
————————————————————————————————————————————————————————
2019.01.24
控制初次加载页面时,当前editext不获取光标,并且点击弹出键盘的效果:
在父布局中设置 可获取焦点,并且,触摸时焦距
//父布局中设置:
android:focusable="true"//可焦距
android:focusableInTouchMode="true"//触摸时焦距
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:focusable="true"
android:focusableInTouchMode="true">
<EditText
android:id="@+id/edtInput"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="$文字..."
android:imeOptions="actionSearch"
android:inputType="text"
android:singleLine="true"
android:textSize="13sp" />
</FrameLayout>