I have one button and edittext. I want to close my soft keyboard when user complete input in edittext and press button.
Or any guide or reference link for it.
I have one button and edittext. I want to close my soft keyboard when user complete input in edittext and press button.
Or any guide or reference link for it.
Call this function to hide the system keyboard:
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
I slightly modify response of @Serj Ardovic
private fun hideKeyboard(view: View) {
view?.apply {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
as its really works for my requirement
You can extend all EditText with new function, which will be hide soft keyboard always when focus for EditText is lost. If you want hide keyboard, when focus for some EditText is lost, just use this line of code for this EditText
editText.hideSoftKeyboardOnFocusLostEnabled(true)
In extension for EditText we just add or remove our own OnFocusLostListener
fun EditText.hideSoftKeyboardOnFocusLostEnabled(enabled: Boolean) {
val listener = if (enabled)
OnFocusLostListener()
else
null
onFocusChangeListener = listener
}
Here is implementation of OnFocusLostListener which hides keyboard if focus for attached View is lost.
class OnFocusLostListener: View.OnFocusChangeListener {
override fun onFocusChange(v: View, hasFocus: Boolean) {
if (!hasFocus) {
val imm = v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(v.windowToken, 0)
}
}
}
fun hideSoftKeyboard(mActivity: Activity) {
// Check if no view has focus:
val view = mActivity.currentFocus
if (view != null) {
val inputManager = mActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
fun showKeyboard(yourEditText: EditText, activity: Activity) {
try {
val input = activity
.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
input.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT)
} catch (e: Exception) {
e.printStackTrace()
}
}