Activity初始化onCreate中调用如下方法即可
override fun initUI() {
setSupportActionBar(binding.toolbar)//设置toolbar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//5.x开始需要把颜色设置透明,否则导航栏会呈现系统默认的浅灰色
val window: Window = activity.window
val decorView: View = window.getDecorView()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//fitsSystemWindows过时替代方法--安卓11及以上才有windowInsetsController
decorView.windowInsetsController?.systemBarsBehavior =
WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_SWIPE
} else {
//两个 flag 要结合使用,表示让应用的主体内容占用系统状态栏的空间
val option: Int = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
decorView.systemUiVisibility = option
}
//让view空出状态栏高度
val resourceId =
resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
var statusBarHeight = resources.getDimensionPixelSize(resourceId)
binding.root.setPadding(0, statusBarHeight, 0, 0)
}
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.setStatusBarColor(Color.TRANSPARENT)
//导航栏颜色也可以正常设置
//window.setNavigationBarColor(Color.TRANSPARENT);
}
}
网友评论