I had the problem that my implemantation for AppCompatEditText
was not longer working.
I was using:
class CustomAppCompatEditText : AppCompatEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
clearFocus()
}
return super.onKeyPreIme(keyCode, event)
}
override fun onEditorAction(actionCode: Int) {
if (actionCode == EditorInfo.IME_ACTION_DONE) {
clearFocus()
}
super.onEditorAction(actionCode)
}
}
I created a new class called KeyboardHelper
.
It looks like this:
object KeyboardHelper {
fun View?.clearFocusOnKeyboardHidden() {
var wasOpened = false
val listener = ViewTreeObserver.OnGlobalLayoutListener {
val isOpen = isKeyboardVisible(this@clearFocusOnKeyboardHidden?.context?.getActivity())
if (isOpen == wasOpened) {
// The keyboard state has not changed yet!
return@OnGlobalLayoutListener
}
wasOpened = isOpen
if (this@clearFocusOnKeyboardHidden?.isFocused == true && !isOpen) {
this@clearFocusOnKeyboardHidden.clearFocus()
}
}
this?.viewTreeObserver?.addOnGlobalLayoutListener(listener)
}
private fun isKeyboardVisible(activity: Activity?): Boolean {
activity ?: return false
val outRect = Rect()
val activityRoot = activity.getActivityRoot()
activityRoot.getWindowVisibleDisplayFrame(outRect)
val location = IntArray(2)
activity.getContentRoot().getLocationOnScreen(location)
val screenHeight = activityRoot.rootView.height
val heightDiff = screenHeight - outRect.height() - location[1]
return heightDiff > screenHeight * 0.15
}
private fun Context.getActivity(): Activity? {
return when (this) {
is Activity -> this
is ContextWrapper -> this.baseContext.getActivity()
else -> null
}
}
private fun Activity.getActivityRoot(): View {
return this.getContentRoot().rootView
}
private fun Activity.getContentRoot(): ViewGroup {
return this.findViewById(android.R.id.content)
}
}
Now I had done a few changes to my CustomAppCompatEditText
class:
class CustomAppCompatEditText : AppCompatEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
init {
clearFocusOnKeyboardHidden()
}
override fun onEditorAction(actionCode: Int) {
if (actionCode == EditorInfo.IME_ACTION_DONE) {
clearFocus()
}
super.onEditorAction(actionCode)
}
}
After all it's now working as before again.
The source code of keyboard code was original from here:
https://github.com/yshrsmz/KeyboardVisibilityEvent