看到好多人对“沉浸式”这个词的释义,学到了点,不过这里我只是关注通知栏是否透明,且不影响我APP UI的布局即可。
先来看对比图:
默认的造型:
沉浸式处理后的造型:
实现步骤如下:
Step1. 下载SystemBarTint开源库,拷贝或引入其中的SystemBarTintManager.java至本项目中
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<!--
Base application theme for API 19+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v19/styles.xml on API 19+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.NoActionBar">
<!-- API 19 theme customizations can go here. -->
<item name="android:windowContentOverlay">@null</item>
</style>
</resources>
此处,确认manifest文件中application的android:theme="AppBaseTheme"或继承自“AppBaseTheme”。以保证在Android4.4以上该样式生效。
Step3. 在需要体现沉浸式效果的页面Activity中添加以下代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
// Translucent status bar
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.main_bg_blue);// 通知栏所需颜色
}
}
(此时一般会发现APP的整个界面充满了屏幕,UI顶部的部分原色被通知栏遮盖了一点,透明或半透明),效果如下。
Step4. 实现UI顶部的自适应,从通知栏下方开始显示。
在界面根布局文件中添加
android:fitsSystemWindows="true"
属性,让界面布局适应系统屏幕空间(给状态栏让出位子)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="@color/white"
android:orientation="vertical" >
...
</LinearLayout>
最终效果如对比图所示。
后记
其实不用SystemBarTintManager 库也可以实现上述效果,不过需要对界面布局的背景色做特定设置(根布局需要与状态栏背景色一致),这样工作量有点大,而SystemBarTintManager类可以灵活的设置背景色。(其变更不会影响界面其他元素的背景色)。