Android设置渐变色状态栏

1、先在drawable目录下创建一个渐变色的矩形图片xml文件:com_sswl_gradient_yello.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="0"
        android:endColor="@color/com_sswl_yello_f5aa33"
        android:startColor="@color/com_sswl_yello_f88907"
        android:type="linear"/>
</shape>

2、然后在Activity的布局绘制完成之后,即在onWindowFocusChanged

  @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
            StatusBarUtil.setStatusBarDrawable(this,R.drawable.com_sswl_gradient_yello);
    }

或者在Activity中对窗口的DecorView增加布局变化监听

getWindow().getDecorView().getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
     @Override
     public void onGlobalFocusChanged(View oldFocus, View newFocus) {
        StatusBarUtil.setStatusBarDrawable(this,R.drawable.com_sswl_gradient_yello);        
    }
});

调用反射修改状态栏背景即可

    /**
     * 设置状态栏颜色背景图
     * @param activity
     * @param id
     */
    public static void setStatusBarDrawable(Activity activity, @DrawableRes int id) {
        //利用反射机制修改状态栏背景
        int identifier = activity.getResources().getIdentifier("statusBarBackground", "id", "android");
        View statusBarView = activity.getWindow().findViewById(identifier);
        if (statusBarView != null) {
            statusBarView.setBackgroundResource(id);
        }
    }

【备注】
之所以要在onWindowFocusChanged 或者onGlobalFocusChanged 调用,是因为当切换到其他第三方页面或者主题不一致的页面时候,状态栏状态会被覆盖重置掉,所以要重新设置回来才有效

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值