Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect navigation bar visibility

I am trying to check the visibility of the navigation bar. On the Samsung Galaxy S8 I can toggle the navigation bar visibility.

I have tried a lot of different ways to check the visibility, but none of them work on the Galaxy S8.

Some examples: (They will always return the same value, no matter it is shown or hidden)

ViewConfiguration.get(getBaseContext()).hasPermanentMenuKey() always returns false KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK) always returns false KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME) always returns true

Even by figuring out the navigation bar height (How do I get the height and width of the Android Navigation Bar programmatically?), it will not work.

like image 846
Joery Avatar asked Nov 08 '22 16:11

Joery


1 Answers

Maybe this will be useful for someone. The user can hide the navigation bar, so the best way to detect visibility is to subscribe to this event. It works.

 object NavigationBarUtils {
    // Location of navigation bar
    const val LOCATION_BOTTOM = 0
    const val LOCATION_RIGHT = 1
    const val LOCATION_LEFT = 2
    const val LOCATION_NONE = 3

    fun addLocationListener(activity: Activity, listener: (location: Int) -> Unit) {
        ViewCompat.setOnApplyWindowInsetsListener(activity.window.decorView) { view, insets ->
            val location = when {
                insets.systemWindowInsetBottom != 0 -> LOCATION_BOTTOM
                insets.systemWindowInsetRight != 0 -> LOCATION_RIGHT
                insets.systemWindowInsetLeft != 0 -> LOCATION_LEFT
                else -> LOCATION_NONE
            }
            listener(location)
            ViewCompat.onApplyWindowInsets(view, insets)
        }
    }
}
like image 181
Andrey Tuzov Avatar answered Nov 15 '22 06:11

Andrey Tuzov