Skip to content

Instantly share code, notes, and snippets.

@luisenricke
Created February 4, 2020 18:22
Show Gist options
  • Save luisenricke/d3e6faf3e320b66769ca319618a36f84 to your computer and use it in GitHub Desktop.
Save luisenricke/d3e6faf3e320b66769ca319618a36f84 to your computer and use it in GitHub Desktop.
Android: hide keyboard
@Suppress("unused")
abstract class BaseActivity : AppCompatActivity() {
private lateinit var inputMethodManager: InputMethodManager
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
}
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
if (ev?.action == MotionEvent.ACTION_DOWN) {
val actual = currentFocus
if (actual is TextInputEditText) {
val borderView = Rect()
actual.getGlobalVisibleRect(borderView)
if (!borderView.contains(ev.rawX.toInt(), ev.rawY.toInt())) {
inputMethodManager.hideSoftInputFromWindow(actual.windowToken, 0)
}
}
}
return super.dispatchTouchEvent(ev)
}
fun hideKeyboard(){
inputMethodManager.hideSoftInputFromWindow(currentFocus?.windowToken, 0)
}
fun showKeyboard(){
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment