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 调用,是因为当切换到其他第三方页面或者主题不一致的页面时候,状态栏状态会被覆盖重置掉,所以要重新设置回来才有效