1.5.0以上调用下面的代码就可以完成着色的处理
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//5.0 以上
View decorView = activity.getWindow().getDecorView();
//添加View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN是为了让布局衍生到状态栏,如果不想衍生,去掉即可
//View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 是在6.0以上才有效果,目的是为了将状态栏的字体和图标换成灰色
// int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
// decorView.setSystemUiVisibility(option);
//设置状态栏的颜色 activity.getWindow().setStatusBarColor(activity.getResources().getColor(color));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4 to 5.0
//4.4 This is just to make the status bar transparent, the layout will be derived from the status bar
WindowManager.LayoutParams localLayoutParams = activity.getWindow().getAttributes();
localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
}
- 4.4到5.0想要完成着色的处理还需要在setContentview之后调用下面的代码
public static void setStatusBar4(Activity activity,int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT&&Build.VERSION.SDK_INT <Build.VERSION_CODES.LOLLIPOP) {
//Let the layout not derived to the status bar
ViewGroup mContentView = (ViewGroup) activity.findViewById(android.R.id.content);
View mChildView = mContentView.getChildAt(0);
if (mChildView != null) {
//设置布局不衍生到状态栏
ViewCompat.setFitsSystemWindows(mChildView, true);
}
//给状态栏添加一个和布局一样颜色的view
addStatusBarView(activity,color,mContentView);
}
}
/**
* Add layout to status bar
* @param color
* @param viewGroup
*/
public static void addStatusBarView(Activity activity,int color,ViewGroup viewGroup) {
View view = new View(activity);
view.setBackgroundColor(activity.getResources().getColor(color));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
statusHeight(activity));
view.setLayoutParams(params);
viewGroup.addView(view);
}
/**
*Get the status bar height
*
* @param activity
* @return
*/
public static int statusHeight(Activity activity) {
int result = 0;
int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = activity.getResources().getDimensionPixelSize(resourceId);
}
return result;
}