现在大多数应用都适配到了5.0以上,将状态栏嵌入进我们的应用是必须的。那就来说说怎样使状态栏变色吧。
1、对于api 5.0及以上
根据你的品牌特征修改调色板,从而自定义 Material 主题。你可以通过主题属性调整 action bar 和状态栏的颜色,就像下图一样:
系统组件拥有新的设计和触摸反馈动画。你可以自定义调色板,反馈动画和 Activity 切换动画。
Material 主题被定义在:
@android:style/Theme.Material
@android:style/Theme.Material.Light
@android:style/Theme.Material.Light.DarkActionBar
想知道可用的 Material style 的列表,可以在 API 文档中参见 R.style.
Note: Material 主题只支持 Android 5.0 (API level 21) 及以上版本。v7 Support 库提供了一些组件的 Material Deisgn 样式,也支持自定义调色板。更多信息,请参见维护兼容性章节。
自定义调色板
在根据自己的品牌自定义调色板时,你需要在继承 material 主题时定义 theme 属性。
<resources>
<!-- inherit from the material theme -->
<style name="AppTheme" parent="android:Theme.Material">
<!-- Main theme colors -->
<!-- your app branding color for the app bar -->
<item name="android:colorPrimary">@color/primary</item>
<!-- darker variant for the status bar and contextual app bars -->
<item name="android:colorPrimaryDark">@color/primary_dark</item>
<!-- theme UI controls like checkboxes and text fields -->
<item name="android:colorAccent">@color/accent</item>
</style>
</resources>
自定义状态栏
Material 主题使得你很容易自定义状态栏,你可以设定适合自己品牌的颜色,并提供足够的对比度,以显示白色的状态图标。设置状态栏颜色时,要在继承 Material 主题时设定 android:statsBarColor
属性。默认情况下,android:statusBarColor
会继承 android:colorPrimaryDark
你也可以在状态栏的背景上绘画。比如,你想让位于照片之上的状态栏透明,并保留一点深色渐变以确保白色图标可见。这样的话,设定 android:statusBarColor
属性为 @android:color/transparent
并调整窗口的 Flag 标记。你也可以用 Window.setStatusBarColor()
Note:
当你自定义导航栏和状态栏时,要么两者都透明,要么只修改状态栏。其他情况下,导航栏应该保持黑色。
主题单独视图
XML layout 中的元素可以定义 android:theme
2、实际开发中兼容5.0以下
用v7 support library自定义调色板,就要应用Theme.AppCompat系列主题:
具体做法:
value下的style.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="BaseAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@android:color/transparent</item>
<item name="colorPrimaryDark">
</item>
<item name="colorAccent">#FF4081</item>
</style>
<style name="AppTheme" parent="@style/BaseAppTheme"/>
</resources>
value-19下的stylexml:
<style name="AppTheme" parent="@style/BaseAppTheme">
<item name="android:windowTranslucentStatus">true</item>
</style>
在大多数的情况下,你可以在布局文件中添加 android:fitsSystemWindows
标签,设置它为true。它会调整父ViewGroup使它留出特定区域给系统栏。
api19的手机的效果图:
5.1的模拟器的效果图:
colorPrimaryDark 为透明,并且在activity中设置内容为全屏。
View decorView = getWindow().getDecorView();
//SYSTEM_UI_FLAG_LAYOUT_STABLE这个标志来帮助你的应用维持一个稳定的布局
//View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN:Activity全屏显示,但状态栏不会被隐藏覆盖,状态栏依然可见,Activity顶端布局部分会被状态遮住。
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
效果同api19一样,用的都是布局的背景色。
api19如果要修改状态栏颜色,用 SystemBarTint。
源码:http://yunpan.cn/c3AdV2QV3Rar7 (提取码:04b0)