Skip to content

Instantly share code, notes, and snippets.

@zakrodionov
Last active November 16, 2021 16:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zakrodionov/fbe5ca9c8e126dcbc47efc3dc78c1e4d to your computer and use it in GitHub Desktop.
Save zakrodionov/fbe5ca9c8e126dcbc47efc3dc78c1e4d to your computer and use it in GitHub Desktop.
Hide keyboard on outside touch (3 popular methods) //Best on top
fun Activity.hideKeyboardOnClickOutsideEditText(view: View) {
// Set up touch listener for non-text box views to hide keyboard.
var previousAction = 0
val onTouchListener = View.OnTouchListener { v, event ->
if (currentFocus != null
&& event.action != MotionEvent.ACTION_DOWN
&& event.action != MotionEvent.ACTION_MOVE
&& previousAction != MotionEvent.ACTION_MOVE
) {
currentFocus?.clearFocus()
v?.hideKeyboard()
}
previousAction = event.action
false
}
if (view !is EditText) {
view.setOnTouchListener(onTouchListener)
}
//If a layout container, iterate over children and seed recursion.
if (view is ViewGroup) {
for (i in 0 until view.childCount) {
val innerView = view.getChildAt(i)
hideKeyboardOnClickOutsideEditText(innerView)
}
}
}
//use currentFocus?.clearFocus() or
//in parent viewgroup layout.xml
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
fun hideKeyboardOutsideTouchEditText(view: View) {
// Set up touch listener for non-text box views to hide keyboard.
val onTouchListener = View.OnFocusChangeListener { v, hasFocus ->
tryOrIgnore {
if (!hasFocus) {
v?.hideKeyboard()
}
}
}
if (view is EditText) {
view.setOnFocusChangeListener(onTouchListener)
}
//If a layout container, iterate over children and seed recursion.
if (view is ViewGroup) {
for (i in 0 until view.childCount) {
val innerView = view.getChildAt(i)
hideKeyboardOutsideTouchEditText(innerView)
}
}
}
or
fun View.hideKeyboardOutsideTouch() {
setOnFocusChangeListener { v, hasFocus ->
if (!hasFocus) {
hideKeyboard()
}
}
}
etAccName.hideKeyboardOutsideTouch()
etDeviceName.hideKeyboardOutsideTouch()
in parent viewgroup layout.xml
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
Activity.kt
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
if (currentFocus != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
}
return super.dispatchTouchEvent(ev)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment