Problem hiding keyboard when scrolling to an EditText field

Viewed 42

I have a ScrollView that contains several EditText and AutoCompleteTextView views. I'd like to hide the keyboard if the user scrolls or taps out of the text box.

So I added this to my Fragments onViewCreated()

myScrollView?.viewTreeObserver?.addOnScrollChangedListener {
            hideKeyboard()
        }

The problem is, when I start scrolling the keyboard hides, BUT when I click an EditText or AutoCompleteTextView, the view starts to scroll to that field to show the keyboard, but because, the scrollview has the addOnScrollChangedListener it hides the keyboard. And the view just jumps back and forth with hiding and showing the keyboard.

What is the correct way to handle this scenario?

The hideKeyboard() comes from an extension class

fun Activity.hideKeyboard() {
    hideKeyboard(currentFocus ?: View(this))
}

fun Context.hideKeyboard(view: View) {
    val inputMethodManager = getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}

fun Fragment.hideKeyboard() {
    view?.let {
        activity?.hideKeyboard(it)
    }
}
0 Answers
Related