android中更改状态栏颜色
楼主今天被QA怼了,真是心塞。
android不同机型的状态栏颜色不一致,QA要求改成一样的。
网上搜索结果有两种方式:
一、透明状态栏
透明状态栏实现方式有两种,一种是写style主题,一种是直接代码设置
1. style主题
首先在manifest中定义application的主题 android:theme=”@style/AppTheme”,然后更改AppTheme,设置android:windowTranslucentStatus,值得注意的是android:windowTranslucentStatus只有api19以上才生效。
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
</resources>
2.直接代码设置
// 经测试在代码里直接声明透明状态栏更有效
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
}
上面两种方式设置完之后都要在xml文件中调整布局添加android:fitsSystemWindows=”true”属性,不添加的话整体的界面会上移。
这种透明状态栏做好之后能保证所有的手机状态栏一致,但是效果是灰色的,视觉效果不是很好看,如果项目有需求就要求更改颜色了。就要自定义状态栏颜色了。
二、自定义状态栏
直接上代码
//判断当前系统版本是否>=Andoird4.4
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//设置状态栏背景状态
//true:表明当前Android系统版本>=4.4
setTranslucentStatus(true);
}
//实例化SystemBarTintManager
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
// 通知标题栏所需颜色
tintManager.setStatusBarTintResource(R.color.colorPrimary);
tintManager.setStatusBarTintResource(R.color.colorPrimary);把colorPrimary改成你要的颜色就行了,换图片也可以。
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
设置完之后修改xml添加属性
android:fitsSystemWindows=”true”