DrawerLayout 这个和普通的ViewGroup设置沉浸式 不一样。
普通的只要设置背景,给一个图片或者颜色,状态栏就会变成相应的背景色。(这是在工程已经设置好了在沉浸式下)。
当你发现用DrawerLayout 作为父容器时,给DrawerLayout 设置背景,状态栏还是系统默认色,起初我修改了主题中的选项
在 styles.xml 里面。
对应的主题下添加
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
colorPrimaryDark 为你定义在colors.xml的颜色。
这样可以通过修改主题颜色达到效果,但是其他控件如果用到这个颜色,也会被修改掉,所以这个不是最佳的。
<!-- 察看源码发现,DrawerLayout 的onDraw里面有画状态栏 -->
@Override public void onDraw(Canvas c) { super.onDraw(c); if (mDrawStatusBarBackground && mStatusBarBackground != null) { final int inset = IMPL.getTopInset(mLastInsets); if (inset > 0) { mStatusBarBackground.setBounds(0, 0, getWidth(), inset); mStatusBarBackground.draw(c); } } }
mStatusBarBackground ,可以通过设置public void setStatusBarBackgroundColor(@ColorInt int color) { mStatusBarBackground = new ColorDrawable(color); invalidate(); }或者public void setStatusBarBackground(int resId) { mStatusBarBackground = resId != 0 ? ContextCompat.getDrawable(getContext(), resId) : null; invalidate(); } 也可以public void setStatusBarBackground(Drawable bg) { mStatusBarBackground = bg; invalidate(); }
这样就不会影响到其他了。