How to check visibility of software keyboard in Android?

前端 未结 30 4508
半阙折子戏
半阙折子戏 2020-11-21 04:43

I need to do a very simple thing - find out if the software keyboard is shown. Is this possible in Android?

30条回答
  •  情深已故
    2020-11-21 05:29

    Wow, We have Good news Android Geeks. And its time to say goodbye to the old way. First I will add official release note to read and know more about these methods/ classes, and then we will see these amazing methods/ classes

    Breaking Note: Do not add these into your release apps, until these classes/ methods are released

    How to check keyboard visibility

    val insets = ViewCompat.getRootWindowInsets(view)
    val isKeyboardVisible = insets.isVisible(Type.ime())
    

    Few other utilities

    How to get the height of Keyboard

    val insets = ViewCompat.getRootWindowInsets(view)
    val keyboardHeight = insets.getInsets(Type.ime()).bottom
    

    How to show/ hide the keyboard

    val controller = view.windowInsetsController
    
    // Show the keyboard
    controller.show(Type.ime())
    
    // Hide the keyboard
    controller.hide(Type.ime())
    

    Note: WindowInsetsController added in API-30, so wait till backward compatible class is not available.

    How to listen to keyboard hide/ show event

    ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
        val isKeyboardVisible = insets.isVisible(Type.ime())
        if (isKeyboardVisible) {
            // Do it when keyboard is being shown
        } else {
            // Do it when keyboard is hidden
        }
    
        // Return the insets to keep going down this event to the view hierarchy
        insets
    }
    

提交回复
热议问题