某些设备上的隐形软导航栏

时间:2018-06-04 23:07:46

标签: android button kotlin softkeys

我想知道设备是否有软导航栏。我为此目的使用以下代码:

        val hasNavBar = resources.getIdentifier("config_showNavigationBar", "bool", "android")
        if(hasNavBar > 0 && resources.getBoolean(hasNavBar)){

            val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
            if (resourceId > 0) {
                ApiHelper.navHeight = resources.getDimensionPixelSize(resourceId)
            }
        }

但在某些没有软导航栏的设备上,resources.getDimensionPixelSize(resourceId)会给出一些高度,hasNavBar为真。

出现此问题的设备是Redmi Note 4 Pro。我不知道其他设备是否有同样的问题。

enter image description here

1 个答案:

答案 0 :(得分:0)

我找到了答案。

stackOverflow中有一些功能不起作用,但这很有效。

How to tell whether an android device has hard keys

fun hasSoftKeys(windowManager: WindowManager): Boolean {
        var hasSoftwareKeys = true

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            val d = context.getWindowManager().getDefaultDisplay()

            val realDisplayMetrics = DisplayMetrics()
            d.getRealMetrics(realDisplayMetrics)

            val realHeight = realDisplayMetrics.heightPixels
            val realWidth = realDisplayMetrics.widthPixels

            val displayMetrics = DisplayMetrics()
            d.getMetrics(displayMetrics)

            val displayHeight = displayMetrics.heightPixels
            val displayWidth = displayMetrics.widthPixels

            hasSoftwareKeys = realWidth - displayWidth > 0 || realHeight - displayHeight > 0x<
        } else {
            val hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey()
            val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
            hasSoftwareKeys = !hasMenuKey && !hasBackKey
        }
        return hasSoftwareKeys
    }