沉浸式状态栏 (kotlin)

object StatusBarKt {

    /**
     * 沉浸式状态栏 > 6.0
     */
    fun fitSystemBar(activity: Activity) {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return

        val window = activity.window
        val decorView = window.decorView
        decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)

        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.statusBarColor = Color.TRANSPARENT

    }

    /**
     * 调整状态栏文字、图标颜色 > 6.0
     * true:白底黑字,false:黑底白字
     */
    fun lightStatusBar(activity: Activity, light: Boolean) {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return
        val window = activity.window
        val decorView = window.decorView
        var visibility = decorView.systemUiVisibility

        visibility = if (light) {
            visibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            visibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() //inv 按位取反
        }

        decorView.systemUiVisibility = visibility
    }

    /**
     * 设置页面最外层布局 FitsSystemWindows 属性
     * @param activity
     * @param value
     */
    fun setFitsSystemWindows(activity: Activity, value: Boolean) {
        val contentFrameLayout = activity.findViewById<View>(R.id.content) as ViewGroup
        val parentView = contentFrameLayout.getChildAt(0)
        if (parentView != null && parentView.fitsSystemWindows != value) {
            parentView.fitsSystemWindows = value
        }
    }
}

使用时

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        StatusBarKt.fitSystemBar(this)
        StatusBarKt.lightStatusBar(this,true)
    }
   override fun onResume() {
        super.onResume()
        //沉浸状态栏需要设置  FitsSystemWindows    需要在setContentView之后
        StatusBarKt.setFitsSystemWindows(this,true)
    }

适用于(android 6.0)及以上

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值