Change status bar color with AppCompat ActionBarActivity

后端 未结 7 1628
一个人的身影
一个人的身影 2020-11-29 17:04

In one of my Activities, I changed the Toolbar color using Palette. But on 5.0 devices using ActionBarActivity the status bar color i

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 17:47

    [Kotlin version] I created this extension that also checks if the desired color has enough contrast to hide the System UI, like Battery Status Icon, Clock, etc, so we set the System UI white or black according to this.

    fun Activity.coloredStatusBarMode(@ColorInt color: Int = Color.WHITE, lightSystemUI: Boolean? = null) {
        var flags: Int = window.decorView.systemUiVisibility // get current flags
        var systemLightUIFlag = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        var setSystemUILight = lightSystemUI
    
        if (setSystemUILight == null) {
            // Automatically check if the desired status bar is dark or light
            setSystemUILight = ColorUtils.calculateLuminance(color) < 0.5
        }
    
        flags = if (setSystemUILight) {
            // Set System UI Light (Battery Status Icon, Clock, etc)
            removeFlag(flags, systemLightUIFlag)
        } else {
            // Set System UI Dark (Battery Status Icon, Clock, etc)
            addFlag(flags, systemLightUIFlag)
        }
    
        window.decorView.systemUiVisibility = flags
        window.statusBarColor = color
    }
    
    private fun containsFlag(flags: Int, flagToCheck: Int) = (flags and flagToCheck) != 0
    
    private fun addFlag(flags: Int, flagToAdd: Int): Int {
        return if (!containsFlag(flags, flagToAdd)) {
            flags or flagToAdd
        } else {
            flags
        }
    }
    
    private fun removeFlag(flags: Int, flagToRemove: Int): Int {
        return if (containsFlag(flags, flagToRemove)) {
            flags and flagToRemove.inv()
        } else {
            flags
        }
    }
    

提交回复
热议问题