How do I detect if software keyboard is visible on Android Device or not?

前端 未结 30 1880
情书的邮戳
情书的邮戳 2020-11-22 10:59

Is there a way in Android to detect if the software (a.k.a. \"soft\") keyboard is visible on screen?

30条回答
  •  独厮守ぢ
    2020-11-22 11:33

    This should work if you need to check keyboard status:

    fun Activity.isKeyboardOpened(): Boolean {
        val r = Rect()
    
        val activityRoot = getActivityRoot()
        val visibleThreshold = dip(UiUtils.KEYBOARD_VISIBLE_THRESHOLD_DP)
    
        activityRoot.getWindowVisibleDisplayFrame(r)
    
        val heightDiff = activityRoot.rootView.height - r.height()
    
        return heightDiff > visibleThreshold;
    }
    
    fun Activity.getActivityRoot(): View {
        return (findViewById(android.R.id.content)).getChildAt(0);
    }
    

    Where UiUtils.KEYBOARD_VISIBLE_THRESHOLD_DP = 100 and dip() is an anko func that convert dpToPx:

    fun dip(value: Int): Int {
        return (value * Resources.getSystem().displayMetrics.density).toInt()
    }
    

提交回复
热议问题