I have two edit text in my fragment where users can enter their age and weight. Based on age and weight I calculate how much water user should drink
When I try to call hide keyboard function on afterTextChanged, the keyboard gets hidden after user typed her first character.
How can I hide the keyboard when user actually finished typing?
P.S: there is a maxLength in my edit text 2 for age and 3 for weight, maybe this could be useful information when you are thinking about your recommendation
My code for edit texts with onChange extension function
//change listener extension for TextInputEditText
fun TextInputEditText.onChange(cb: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
cb(s.toString())
hideKeyboard()
}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
// change listener is called with agehandler function with user type age
// I check if the edit text is empty or not
binding.ageEditText.onChange {
if (binding.ageEditText.text.isNullOrEmpty()) {
Snackbar.make(binding.root, "Please type your age", Snackbar.LENGTH_SHORT).show()
} else dashboardViewModel.ageHandler(it)
}
fun hideKeyboard() {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view!!.windowToken, 0)
}