第一种方式
第一种方式,需要做下面三步设置
1、在values、values-v19、values-v21的style.xml都设置一个 Translucent System Bar 风格的Theme
values/style.xml
values-v19/style.xml
true
true
values-v21/style.xml
false
true
@android:color/transparent
上面需要注意的地方是,无论你在哪个SDK版本的values目录下,设置了主题,都应该在最基本的values下设置一个同名的主题。这样才能确保你的app能够正常运行在 Android 4.4 以下的设备。否则,肯定会报找不到Theme的错误。
2、在AndroidManifest.xml中对指定Activity的theme进行设置
android:name=".ui.ImageTranslucentBarActivity"
android:label="@string/image_translucent_bar"
android:theme="@style/ImageTranslucentTheme" />
3、在Activity的布局文件中设置背景图片,同时,需要把android:fitsSystemWindows设置为true
activity_image_translucent_bar.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/env_bg"
android:fitsSystemWindows="true">
到此,第一种实现方式完成,大家可以看看下面的效果
ImageTranslucentTheme效果
就跟中华万年历的天气预报效果界面一样,系统的整个导航栏都融入了app的界面中,背景图片填满了整个屏幕,看起来舒服很多。这里还有一个android:fitsSystemWindows设置需要注意的地方,后面会在细讲。接下来看第二种实现。
方式二
相比中华万年历,QQ音乐采用的是另外一种实现的方式,它将app的Tab栏和系统导航栏分开来设置。
QQ音乐效果风格
由于它的Tab栏是纯色的,所以只要把系统通知栏的颜色设置和Tab栏的颜色一致即可,实现上相比方法一要简单很多。同样要到不同SDK版本的values下,创建一个同名的theme,在values-v21下,需要设置系统导航栏的颜色:
values-v21/style.xml
false
true
@color/color_31c27c
再到ColorTranslucentBarActivity的布局文件activity_color_translucent_bar.xml中设置Tab栏的颜色
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="@color/color_31c27c">
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" />
到此,我们就可以得到和QQ音乐主界面一样的效果了。
QQ音乐界面实现效果
到此,就大体介绍完了 Translucent System Bar 的两种实现方式了。
android:fitsSystemWindows的“踩坑”
通过前面的两种方式,大家估计会留意到一个地方,就是所有实现 Translucent System Bar 效果的Activity,都需要在根布局里设置 android:fitsSystemWindows="true" 。设置了该属性的作用在于,不会让系统导航栏和我们app的UI重叠,导致交互问题。这样说可能比较抽象,看看下面两个效果图的对比就知道了。
有fitsSystemWindows设置
没有fitsSystemWindows设置
还有需要注意用到Translucent system bar时,activity的顶层布局必须是基本的布局,比如,如果直接用material design里面的CoordinatorLayout做顶层布局时,会出现一些异常问题。