安卓开发优雅地获取系统导航栏高度
不要写什么反射系统 View 什么的啦,MIUI 让你头秃。这个适配了,发现那个又没~
使用 WindowInsets 获取系统导航栏高度
在 Activity 的 onCreate 方法中对根布局使用。
// 这里使用了 ViewBinding
binding.root.setOnApplyWindowInsetsListener { _, insets ->
// insets.systemWindowInsetBottom 在新 API 30 中被废弃,通过 API 判断更改不同方法
val navigationBarHeight =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
insets.getInsets(WindowInsets.Type.navigationBars()).bottom
} else {
insets.systemWindowInsetBottom
}
insets
}
navigationBarHeight 获取到状态栏高度,单位为 px 。
本文介绍如何在Android开发中避免使用反射,利用新API WindowInsets获取系统导航栏高度,适用于API 30及以上版本,并提供兼容旧版本的方法。
662

被折叠的 条评论
为什么被折叠?



