I recommend using a LifecycleObserver which is part of the Handling Lifecycles with Lifecycle-Aware Components of Android Jetpack.
I want to open and close the Keyboard when the Fragment/Activity appears. Firstly, define two extension functions for the EditText. You can put them anywhere in your project:
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)
}
Then define a LifecycleObserver which opens and closes the keyboard when the Activity/Fragment reaches onResume()
or 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()
}
}
Then add the following line to any of your Fragments/Activities, you can reuse the LifecycleObserver any times. E.g. for a Fragment:
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
}