Android沉浸式导航栏 android:fitsSystemWindows 属性失效问题

365 阅读1分钟

A. android:fitsSystemWindows 属性详解

郭神的《再学一遍android:fitsSystemWindows属性》

B. 失效原因

原因有很多,但大致分为以下几类,鄙人没有去一一验证,仅供大家参考

1. 布局高度问题**

高度不能写死,只能使用 match_parentwrap_content

2. 多Fragment中使用时的底层事件分发问题

分发过程被消费后不再分发重写事件分发逻辑

C. 通用且稳定的解决方案

不使用官方API,借鉴前端屏幕安全距离的思维,给页面设置上下左右的 MarginPadding,使页面交互控件安全地显示在导航栏下方的安全区域

1. 解决方案

//这里只给出竖屏顶部安全距离获取函数,亲测可用
    fun getSafeTopArea(activity: Activity,targetView:View,callBack:(Int) -> Unit){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            targetView.setOnApplyWindowInsetsListener { _, insets ->
                callBack.invoke(insets.getInsets(WindowInsets.Type.systemBars()).top)
                insets
            }
        }else{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                callBack.invoke(activity.window.decorView.rootWindowInsets.systemWindowInsetTop)
            } else {
                val insets = ViewCompat.getRootWindowInsets(targetView)?.getInsets(
                    WindowInsetsCompat.Type.systemBars())
                    ?: Insets.of(0, 0, 0, 0)
                callBack.invoke(insets.top)
            }
        }
    }

3.使用

getSafeTopArea(requireActivity(),viewBinding.titleBar){
	Log.d("屏幕顶部安全距离",it.toString())
    viewBinding.root.setPadding(0,it,0,0)
}