Android 4.4 以上实现透明导航栏和状态栏 Translucent system bar
时间:2023-06-04 00:37:00
第一种方式
第一种方法需要设置以下三个步骤
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-v系统导航栏的颜色系统导航栏的颜色:
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做顶层布局时,会出现一些异常问题。