Android实战经验分享之如何获取状态栏和导航栏的高度

本文首发于公众号"AntDream",欢迎微信搜索"AntDream"或扫描文章底部二维码关注,和我一起每天进步一点点

在 Android 应用开发中,有时我们需要知道状态栏和导航栏的高度,以便在布局中进行调整。获取这些高度的方法有几种,每种方法在准确性和兼容性方面有所不同。下面我们将详细介绍这几种方法,并提供 Kotlin 代码示例。

获取状态栏高度的方法

方法一:通过资源名称获取

这种方法最常见,也最推荐,具有较高的准确性和兼容性。

kotlin 复制代码
fun getStatusBarHeight(context: Context): Int {
    var result = 0
    val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
    if (resourceId > 0) {
        result = context.resources.getDimensionPixelSize(resourceId)
    }
    return result
}

方法二:通过 WindowInsets 获取

这种方法需要 API 20 (Android 4.4W) 以上,但在较新版本的 Android(API 21及以上)中更为准确。

kotlin 复制代码
fun getStatusBarHeight(activity: Activity): Int {
    val windowInsets = activity.window.decorView.rootWindowInsets
    return windowInsets?.systemWindowInsetTop ?: 0
}

注意:在 Android 11(API 30)及以上版本可以使用 WindowInsetsCompat 进行更兼容性友好的操作。

kotlin 复制代码
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.ViewCompat

fun getStatusBarHeight(activity: Activity): Int {
    val insets = ViewCompat.getRootWindowInsets(activity.window.decorView)
    return insets?.systemWindowInsetTop ?: 0
}

获取导航栏高度的方法

方法一:通过资源名称获取

这种方法和获取状态栏高度的方式类似。

kotlin 复制代码
fun getNavigationBarHeight(context: Context): Int {
    var result = 0
    val resourceId = context.resources.getIdentifier("navigation_bar_height", "dimen", "android")
    if (resourceId > 0) {
        result = context.resources.getDimensionPixelSize(resourceId)
    }
    return result
}

方法二:通过 WindowInsets 获取

这种方法也是较为现代的方式,但需要更高的 API 级别。

kotlin 复制代码
fun getNavigationBarHeight(activity: Activity): Int {
    val windowInsets = activity.window.decorView.rootWindowInsets
    return windowInsets?.systemWindowInsetBottom ?: 0
}

同样地,可以使用 WindowInsetsCompat 进行兼容性处理:

kotlin 复制代码
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.ViewCompat

fun getNavigationBarHeight(activity: Activity): Int {
    val insets = ViewCompat.getRootWindowInsets(activity.window.decorView)
    return insets?.systemWindowInsetBottom ?: 0
}

对比和总结

1、 通过资源名称获取:

  • 优点:简单、代码兼容性好。
  • 缺点:可能受某些定制 ROM 的影响,准确性在极少数情况下可能有问题。

2、 通过 WindowInsets 获取:

  • 优点:在较新版本的 Android 上非常准确。
  • 缺点:需要较新的 API 级别,可能需要做额外的兼容性处理。

兼容性建议

  • 对于支持的最低 API 级别较低的应用,建议优先使用通过资源名称获取的方法,因为这种方法在大多数情况下效果良好。
  • 对于支持较高 API 级别的应用,可以考虑优先使用 WindowInsetsWindowInsetsCompat,以确保准确性。

欢迎关注我的公众号AntDream查看更多精彩文章!

相关推荐
小羊没烦恼!2 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
俊昭喜喜里2 天前
java中的继承和多态的区别
java
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
譕痕2 天前
JSONObject与JSONArray封装数据格式区别
java·json
千里马学框架2 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台2 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
胡写代码2 天前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖2 天前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商
AFinalStone2 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
此时不提桶,更待何时2 天前
01-06-A-JVM排查实战详解
java·jvm