1.导入外部依赖包
implementation 'com.readystatesoftware.systembartint:systembartint:1.0.3'
2.在color.xml中添加app的主题颜色(或者添加自己的目标颜色)
<color name="colorAppTheme">#03A9F4</color>
3.开发工具类,实现状态栏的颜色改变
public class WindowUtils {
public static void initWindow(Activity activity) {//初始化,将状态栏和标题栏设为透明
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
SystemBarTintManager tintManager = new SystemBarTintManager(activity);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintColor(activity.getColor(R.color.colorAppTheme));//此处引用color.xml的资源
}
}
4.在activity的onCreate方法中调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WindowUtils.initWindow(this);//设置手机的状态栏颜色
}
5.效果图
追加部分
还有个比较重要的步骤忘记说了,必须在style.xml文件中AppTheme中引入
<item name="android:fitsSystemWindows">true</item> 否则,如果不执行此步骤,app顶部就会与状态栏重合,这个步骤就是使app支持自定义状态栏,让app处于状态栏的下边。
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#03A9F4</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">#2B2A2A</item>
<!--导航栏上的标题颜色,这里的颜色还可以自己定义喜欢的类型-->
<item name="android:fitsSystemWindows">true</item>
<item name="android:textColorPrimary">#000000</item>
</style>