android:fitsSystemWindows
设置android:fitsSystemWindows生效的前提是控件对于属性有相应的处理,如果没有处理则不会生效。
CoordinatorLayout:处理了沉浸式状态栏并且预留了状态栏高度
CollapsingToolbarLayout:结合CoordinatorLayout可以实现内部控件填充到状态栏
未处理android:fitsSystemWindows属性的控件需要自行处理
处理可交换控件被状态栏遮挡(预留空间)
val button = findViewById<Button>(R.id.button)
ViewCompat.setOnApplyWindowInsetsListener(button) { view, insets ->
val params = view.layoutParams as FrameLayout.LayoutParams
params.topMargin = insets.systemWindowInsetTop
insets
}
浅色状态栏(字体黑色):
val flags = window.decorView.systemUiVisibility
window.decorView.systemUiVisibility = flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
恢复深色状态栏(字体白色):
发了flags = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
window.decorView.systemUiVisibility = flags xor View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
利用Palette库动态获取图像颜色设置状态栏字体颜色:
implementation 'androidx.palette:palette:1.0.0'
Palette
.from(bitmap)//接收图片bitmap
.setRegion(left, top, right, bottom)//指定提取色值区域
.maximumColorCount(colorCount)//设置要提取的色值特征点数
.generate {//获取异步解析结果
it?.let { palette ->
var mostPopularSwatch: Palette.Swatch? = null
for (swatch in palette.swatches) {//循环判断获取权重最高色值
if (mostPopularSwatch == null
|| swatch.population > mostPopularSwatch.population) {
mostPopularSwatch = swatch
}
}
mostPopularSwatch?.let { swatch ->
val luminance = ColorUtils.calculateLuminance(swatch.rgb)
// 当luminance小于0.5时,认为这是一个深色值.
if (luminance < 0.5) {
setDarkStatusBar()
} else {
setLightStatusBar()
}
}
Android11之后设置:
使用WindowInsetsController需要core版本提高到1.5.0以上
API详细说明(需要vpn查看)
https://developer.android.com/reference/android/view/WindowInsetsController?hl=en
控制状态栏:
implementation 'androidx.core:core:1.5.0-alpha05'
//初始化WindowInsetsController
val controller = ViewCompat.getWindowInsetsController(view)
//显示状态栏
controller?.show(WindowInsetsCompat.Type.statusBars())
//隐藏状态栏
controller?.hide(WindowInsetsCompat.Type.statusBars())
//设置状态栏文字黑色
controller?.isAppearanceLightStatusBars = true
//设置状态栏文字白色
controller?.isAppearanceLightStatusBars = false
控制导航栏:
//显示
controller?.show(WindowInsetsCompat.Type.navigationBars())
//隐藏
controller?.hide(WindowInsetsCompat.Type.navigationBars())
//导航栏隐藏时手势操作
controller?.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
//systemBarsBehavior有三个值:
BEHAVIOR_SHOW_BARS_BY_SWIPE
BEHAVIOR_SHOW_BARS_BY_TOUCH
BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
目前可能跟部分手机手势有冲突
控件键盘:
需要界面有EditText并且EditText获取到焦点才能起作用
//显示键盘
controller?.show(WindowInsetsCompat.Type.ime())
//隐藏键盘
controller?.hide(WindowInsetsCompat.Type.ime())
操作所有系统栏:
//全屏显示:
controller?.hide(WindowInsetsCompat.Type.systemBars())
//显示其他系统栏:
controller?.show(WindowInsetsCompat.Type.systemBars())