先看对比图
非沉浸式通知栏
Android 4.4开始,引入了Translucent System Bar的系特性,用于弥补系统通知栏突兀之处。
沉浸式通知栏1
沉浸式通知栏2
沉浸式通知栏看起来效果更好
只需四步完成沉浸式通知栏
1 在values、values-v19、values-v21的style.xml都设置一个 Translucent System Bar 风格的Theme
values/style.xml
<style name="ImageTranslucentTheme" parent="AppTheme">
<!--在Android 4.4之前的版本上运行,直接跟随系统主题-->
</style>
values-v19/style.xml
<style name="ImageTranslucentTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
values-v21/style.xml
<style name="ColorTranslucentTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowTranslucentStatus">false</item>
<item name="android:windowTranslucentNavigation">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
上面需要注意的地方是,无论你在哪个SDK版本的values目录下,设置了主题,都应该在最基本的values下设置一个同名的主题。这样才能确保你的app能够正常运行在 Android 4.4 以下的设备。否则,肯定会报找不到Theme的错误。
2 在AndroidManifest.xml中对指定Activity的theme进行设置
ColorTranslucentTheme.xml
<activity
android:name=".ui.ImageTranslucentBarActivity"
android:label="@string/image_translucent_bar"
android:theme="@style/ImageTranslucentTheme" />
3 隐藏状态栏
public class BaseActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
4 在Activity的布局文件中设置背景图片或颜色,同时,需要把android:fitsSystemWindows设置为true
设置图片
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/env_bg"
android:fitsSystemWindows="true">
</RelativeLayout>
效果如下
就跟中华万年历的天气预报效果界面一样,系统的整个导航栏都融入了app的界面中,背景图片填满了整个屏幕,看起来舒服很多。这里还有一个android:fitsSystemWindows设置需要注意的地方。
设置颜色
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/color_31c27c"
android:fitsSystemWindows="true"
android:orientation="vertical">
<!--标题布局-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="@color/color_31c27c">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="QQ Music"
android:textColor="@android:color/white"
android:textSize="20sp" />
</RelativeLayout>
</LinearLayout>
效果如下
相比中华万年历,QQ音乐采用的是另外一种实现的方式,它将app的Tab栏和系统导航栏分开来设置。
由于它的Tab栏是纯色的,所以只要把系统通知栏的颜色设置和Tab栏的颜色一致即可。
android:fitsSystemWindows的“踩坑”
通过前面的两种方式,大家估计会留意到一个地方,就是所有实现 Translucent System Bar 效果的Activity,都需要在根布局里设置 android:fitsSystemWindows=”true” 。设置了该属性的作用在于,不会让系统导航栏和我们app的UI重叠,导致交互问题。这样说可能比较抽象,看看下面两个效果图的对比就知道了。