android中更改状态栏颜色

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”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值