一行代码使Android状态栏变沉浸式透明化

public static void setStatusBarColor(Activity activity, int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
ViewGroup decorViewGroup = (ViewGroup) activity.getWindow().getDecorView();
//获取自己布局的根视图
View rootView = ((ViewGroup) (decorViewGroup.findViewById(android.R.id.content))).getChildAt(0); //预留状态栏位置
rootView.setFitsSystemWindows(true); //添加状态栏高度的视图布局,并填充颜色
View statusBarTintView = new View(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
PhoneInfo.getInternalDimensionSize(activity.getResources(), "status_bar_height"));
params.gravity = Gravity.TOP;
statusBarTintView.setLayoutParams(params);
statusBarTintView.setBackgroundColor(color);
decorViewGroup.addView(statusBarTintView);
}
} public static int getInternalDimensionSize(Resources res, String key) {
int result = 0; int resourceId = res.getIdentifier(key, "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
return result;
}
}

以后就只需要在Activity中添加这一行代码,不用修改其他地方,第一个参数为Activity,第二个为颜色Id:

PhoneInfo.setStatusBarColor(this,getResources().getColor(android.R.color.holo_blue_light));

注意一定要设置在setContentView()方法之后,如:

setContentView(R.layout.layout);  
PhoneInfo.setStatusBarColor(this, getResources().getColor(R.color.blue));
posted @ 2017-11-13 13:39  想不起来的角落  阅读(404)  评论(0编辑  收藏  举报