一、沉浸式状态栏Immersive Mode
开源库SystemBarTint很好的实现了沉浸式状态栏,该开源库的使用也非常方便。下载该库,设置项目依赖即可。本demo我没有使用项目依赖方式,直接将SystemBarTintManager.java文件copy至本地。
由于半透明状态栏只能在android 19以上能用,所以需要判断版本:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
}
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.status_bar_color);
使用 SystemBarTintManager需要将状态栏设置为透明状态,方法setTranslucentStatus(true)为:
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
另外,还需要在xml的布局文件的根目录设置属性:
android:fitsSystemWindows="true"
该属性避免内容区域显示在状态栏上。
二、透明状态栏
沉浸式状态栏是半透明效果,状态栏上覆盖一层其他颜色,影响效果。因此可以使用全透明效果,全透明只支持android 21以上版本,所以使用时仍需要判断版本号:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//设置全透明状态栏
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.parseColor("#4A76F9")); //设置状态栏颜色
window.setNavigationBarColor(Color.TRANSPARENT);
}
另外,全透明效果也需要在xml的布局文件的根目录设置属性:
android:fitsSystemWindows="true"
so,可以在21以上设置全透明,19-21设置沉浸式:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//Android 21以上版本设置全透明状态栏
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.parseColor("#4A76F9")); //设置状态栏颜色
window.setNavigationBarColor(Color.TRANSPARENT);
}else {
//android 19以上版本设置沉浸式状态栏
setTranslucentStatus(true);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.status_bar_color);
}
}