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

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

在 Android 应用开发中,有时我们需要知道状态栏和导航栏的高度,以便在布局中进行调整。获取这些高度的方法有几种,每种方法在准确性和兼容性方面有所不同。下面我们将详细介绍这几种方法,并提供 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及以上)中更为准确。

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

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

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
}

获取导航栏高度的方法

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

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

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 级别。

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

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

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查看更多精彩文章!

AntDream

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值