沉浸式状态栏Immersive Mode & 透明式状态栏Translucent Bars

来源:互联网 发布:linux系统解压缩文件 编辑:程序博客网 时间:2024/04/30 18:52

一、沉浸式状态栏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);}}







0 0