https://kotlinlang.org logo
#android
Title
# android
r

ribesg

03/19/2019, 3:50 PM
Do we still have no proper keyboard show/hide event handling on Android in 2019? /rant
😁 1
👍 3
stackoverflow 3
Anyone got a better way of doing it than this?
Copy code
inline fun View.onKeyboardStateChanged(crossinline action: (visible: Boolean) -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {

        private val estimatedSoftKeyboardHeight = 100
        private val density = resources.displayMetrics.density
        private val visibleRect = Rect()
        private var isKeyboardShown = false

        override fun onGlobalLayout() {
            if (isKeyboardShown() != isKeyboardShown) {
                isKeyboardShown = !isKeyboardShown
                action(isKeyboardShown)
            }
        }

        private fun isKeyboardShown(): Boolean {
            rootView.getWindowVisibleDisplayFrame(visibleRect)
            return rootView.bottom - visibleRect.bottom > estimatedSoftKeyboardHeight * density
        }

    })
}
d

dalexander

03/19/2019, 4:48 PM
That looks like how I had to handle that problem almost five years ago 😞
l

louiscad

03/19/2019, 11:49 PM
Maybe at Google I/O they will uncover a solution for that (they talked about their intentions to make this easier), but for now, that's about all we got.
a

ahulyk

03/20/2019, 9:38 AM
i have heard that Google gona fix this in 2019 🙂 Looking forward to see solution at I/O
Copy code
fun Activity.openKeyboard() {
    try {
        getSystemService<InputMethodManager>()?.showSoftInput(currentFocus, SHOW_IMPLICIT)
    } catch (e: Exception) {
    }
}

fun Activity.closeKeyboard() {
    try {
        getSystemService<InputMethodManager>()?.hideSoftInputFromWindow(
            currentFocus?.windowToken, HIDE_NOT_ALWAYS
        )
    } catch (e: Exception) {
    }
}
r

ribesg

03/20/2019, 9:48 AM
Well I do know how to open and close the keyboard, that’s not what’s missing in Android 🤷‍♂️
5 Views