How to capture the “virtual keyboard show/hide” event in Android?

前端 未结 16 1194
暗喜
暗喜 2020-11-22 07:23

I would like to alter the layout based on whether the virtual keyboard is shown or not. I\'ve searched the API and various blogs but can\'t seem to find anything useful.

16条回答
  •  清酒与你
    2020-11-22 08:18

    using viewTreeObserver for easily get the keyboard event.

    layout_parent.viewTreeObserver.addOnGlobalLayoutListener {
                val r = Rect()
                layout_parent.getWindowVisibleDisplayFrame(r)
                if (layout_parent.rootView.height - (r.bottom - r.top) > 100) { // if more than 100 pixels, its probably a keyboard...
                    Log.e("TAG:", "keyboard open")
                } else {
                    Log.e("TAG:", "keyboard close")
                }
            }
    

    ** layout_parent is your view like edit_text.parent

提交回复
热议问题