我建议使用LifecycleObserver这是一部分具有生命周期感知组件处理生命周期的安卓Jetpack的。
片段/活动出现时,我想打开和关闭键盘。首先,为EditText 定义两个扩展功能。您可以将它们放在项目中的任何位置:
fun EditText.showKeyboard() {
requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun EditText.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(this.windowToken, 0)
}
然后定义一个LifecycleObserver,当Activity / Fragment到达onResume()
或时,它将打开和关闭键盘onPause
:
class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun openKeyboard() {
editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun closeKeyboard() {
editText.get()?.hideKeyboard()
}
}
然后将以下行添加到您的任何片段/活动中,您可以随时重复使用LifecycleObserver。例如片段:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// inflate the Fragment layout
lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))
// do other stuff and return the view
}