Created
February 4, 2020 18:22
-
-
Save luisenricke/d3e6faf3e320b66769ca319618a36f84 to your computer and use it in GitHub Desktop.
Android: hide keyboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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