如果您不想使用xml,请创建Kotlin Extension以隐藏键盘
// In onResume, call this
myView.hideKeyboard()
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
根据用例的替代方案:
fun Fragment.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
fun Activity.hideKeyboard() {
// Calls Context.hideKeyboard
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
view.hideKeyboard()
}
如何显示软键盘
fun Context.showKeyboard() { // Or View.showKeyboard()
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
}
同时请求将焦点放在edittext上的更简单方法
myEdittext.focus()
fun View.focus() {
requestFocus()
showKeyboard()
}
简化奖金:
删除使用过的要求getSystemService
:Splitties库
// Simplifies above solution to just
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
android:windowSoftInputMode="stateHidden"