如果您不想使用 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)
}
同时请求对编辑文本的关注时更简单的方法
myEdittext.focus()
fun View.focus() {
requestFocus()
showKeyboard()
}
奖金简化:
删除永远使用的要求getSystemService
:Splitties Library
// Simplifies above solution to just
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)