網(wǎng)上有很多第三方的改變狀態(tài)欄顏色的代碼,寫(xiě)法也不一樣叫榕,今天我們自己來(lái)寫(xiě)一套熄赡,適配到Android4.4以上。
1.android5.0以上執(zhí)行語(yǔ)句
5.0以上有系統(tǒng)的方法兼贸,比較好實(shí)現(xiàn)如下:
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
//直接調(diào)用系統(tǒng)的方法
activity.getWindow().setStatusBarColor(color);
}
2.android4.4以上到5.0以下適配
因?yàn)閍ndroid4.4以上到5.0以下系統(tǒng)沒(méi)有提供方法段直,需要自己去實(shí)現(xiàn),具體的實(shí)現(xiàn)思路--》把它設(shè)成全屏 寝受,在狀態(tài)欄加一個(gè)布局
設(shè)置全屏
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
添加一個(gè)布局
//狀態(tài)欄添加一個(gè)布局
View view=new View(activity);
ViewGroup.LayoutParams params= new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
view.setLayoutParams(params );
view.setBackgroundColor(color);
ViewGroup decorView= (ViewGroup) activity.getWindow().getDecorView();
decorView.addView(view, 0);
ViewGroup contentView=(ViewGroup) activity.findViewById(android.R.id.content);
View activityView = contentView.getChildAt(0);
activityView.setFitsSystemWindows(true);
3.獲取狀態(tài)欄高度
private static int getStatusBarHeight(Activity activity){
//先獲取資源id坷牛,根據(jù)資源ID獲取資源
Resources resources= activity.getResources();
int identifier = resources.getIdentifier("status_bar_height", "dimen", "android");
return resources.getDimensionPixelOffset(identifier);
}
其實(shí)就那么簡(jiǎn)單,下面提供以下完整代碼
public class StatusBarUtil {
/**
*
* @param activity
* @param color
*/
public static void setStatusBarColor(Activity activity,int color){
//5.0以上
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
//直接調(diào)用系統(tǒng)的方法
activity.getWindow().setStatusBarColor(color);
}else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
//4.4-5.0之間 采用一個(gè)技巧 很澄,首先把他能成全屏 京闰,在狀態(tài)欄加一個(gè)布局
//設(shè)置全屏
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//狀態(tài)欄添加一個(gè)布局
View view=new View(activity);
ViewGroup.LayoutParams params= new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
view.setLayoutParams(params );
view.setBackgroundColor(color);
ViewGroup decorView= (ViewGroup) activity.getWindow().getDecorView();
decorView.addView(view, 0);
ViewGroup contentView=(ViewGroup) activity.findViewById(android.R.id.content);
//1.方式一
View activityView = contentView.getChildAt(0);
activityView.setFitsSystemWindows(true);
//方式二
// contentView.setPadding(0,getStatusBarHeight(activity),0,0);
//方式三
// activityView.setPadding(0,getStatusBarHeight(activity),0,0);
}
}
/**
* 獲取狀態(tài)欄高度
* @param activity
* @return
*/
private static int getStatusBarHeight(Activity activity){
//先獲取資源id,根據(jù)資源ID獲取資源
Resources resources= activity.getResources();
int identifier = resources.getIdentifier("status_bar_height", "dimen", "android");
return resources.getDimensionPixelOffset(identifier);
}
}