Skip to content

Instantly share code, notes, and snippets.

@MachFour
Last active April 10, 2024 19:41
Show Gist options
  • Save MachFour/c6b5252292dd3bfe18d6b1141f137d32 to your computer and use it in GitHub Desktop.
Save MachFour/c6b5252292dd3bfe18d6b1141f137d32 to your computer and use it in GitHub Desktop.
A (Material) AutoCompleteTextView that automatically hides the keyboard when scrolling the dropdown list. Uses reflection and is very hacky.
package com.machfour.example.app
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.inputmethod.InputMethodManager
import android.widget.AbsListView
import android.widget.AutoCompleteTextView
import android.widget.ListPopupWindow
import com.google.android.material.textfield.MaterialAutoCompleteTextView
import com.machfour.example.app.R // need this for default style
// Extension of MaterialAutoCompleteTextView that automatically hides the soft keyboard
// when the autocomplete dropdown is touched.
class CustomAutoCompleteTextView @JvmOverloads constructor (
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = R.attr.autoCompleteTextViewStyle)
: MaterialAutoCompleteTextView(context, attributeSet, defStyleAttr) {
companion object {
// need to access private field ('mPopup') of AutoCompleteTextView
private val popupWindowField = AutoCompleteTextView::class.java.getDeclaredField("mPopup")
.also { it.isAccessible = true }
}
private val popupWindow = popupWindowField.get(this) as ListPopupWindow
// this function actually hides the keyboard
private fun hideKeyboard() {
val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(rootView.windowToken, 0)
}
// add scroll listener to dropdown in order to hide IME when scrolled
@SuppressLint("ClickableViewAccessibility")
override fun showDropDown() {
super.showDropDown()
// the popup list view shouldn't be null here because the dropdown was just shown
// ... perhaps unless it's empty
popupWindow.listView?.setOnTouchListener { _, _ ->
hideKeyboard()
// have to return false here otherwise scrolling won't work
false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment