Android M Light and Dark status bar programmatically - how to make it dark again?

前端 未结 10 1686
自闭症患者
自闭症患者 2020-12-24 10:49

In the Android M we have ability to make status bar icons dark. To do that we can specify attribute in the theme\'s xml:



        
10条回答
  •  独厮守ぢ
    2020-12-24 11:44

    I put together this simple utility object that allows you to change status bar color and light status bar on/off for within any fragment. However, this relies on using the Android Jetpack Navigation component for navigation (Kotlin):

    object StatusBarUtil {
        fun changeStatusBarColor(activity: Activity, @ColorInt color: Int, lightStatusBar: Boolean) {
            activity.window?.let { win ->
                val nav = Navigation.findNavController(activity, R.id.your_nav_host_fragmen /* TODO: Use the ID of your nav host fragment */)
                val currentDest = nav.currentDestination?.id
                val oldColor = win.statusBarColor
                val oldFlags = win.decorView.systemUiVisibility
                win.statusBarColor = color
    
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    var flags = oldFlags
                    flags = if (lightStatusBar) {
                        flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    } else {
                        flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
                    }
                    win.decorView.systemUiVisibility = flags
                }
    
                nav.addOnNavigatedListener { _, dest ->
                    if (dest.id != currentDest) {
                        win.statusBarColor = oldColor
                        win.decorView.systemUiVisibility = oldFlags
                    }
                }
            }
        }
    }
    

    To use this, call the following from within any fragment's onViewCreated:

    StatusBarUtil.changeStatusBarColor(requireActivity(), someDarkColor, false)
    

提交回复
热议问题