Kotlin listens to the keyboard to show and hide

Recently, I encountered the need to monitor the display and hiding of the keyboard, and encapsulated an extension method in the Kotlin scene for future use.

The Android system itself does not provide an effective method to monitor the display and hide of the keyboard. The most commonly used monitoring method is the height of the visible area of ​​the screen. When the height change exceeds a certain value, generally considered to be more than 200 pixels, it means that the keyboard is displayed and hidden. Hide actions.

fun Activity.observeKeyboardChange(onChange: (isShowing: Boolean) -> Unit) {
    val rootView = this.window.decorView
    val r = Rect()
    var lastHeight = 0
    rootView.viewTreeObserver.addOnGlobalLayoutListener {
        rootView.getWindowVisibleDisplayFrame(r)
        val height = r.height()
        if (lastHeight == 0) {
            lastHeight = height
        } else {
            val diff = lastHeight - height
            if (diff > 200) {
                onChange(true)
                lastHeight = height
            } else if (diff < -200) {
                onChange(false)
                lastHeight = height
            }
        }
    }
}

Fanwai
EditText can be set in xml by inputType="textMultiLine" to enter multi-line text, and by imeOptions="actionDone" to set the button in the lower right corner of the keyboard. There are common settings such as ACTION_DONE, ACTION_SEARCH, and ACTION_SEND.

However, if inputType="textMultiLine" is set, multi-line input is possible. At this time, the button in the lower right corner of the keyboard will default to a newline operation, and the set imeOptions property will be invalid. After searching on the Internet for many times, I finally found an effective way to make inputType="textMultiLine" and imeOptions="actionDone" effective at the same time.

First, set inputType="textMultiLine" in xml;
then, set imeOptions to actionDone through code.

et.imeOptions = EditorInfo.IME_ACTION_DONE
et.setRawInputType(InputType.TYPE_CLASS_TEXT)

Guess you like

Origin blog.csdn.net/yuantian_shenhai/article/details/126084868