沉浸式体验
图中所示就是Android 4.4以后被很多人称之为沉浸式体验的典型场景,即状态栏和ActionBar是同一种颜色;一度我以为这是官方支持的,只需要几句简单的设置就可以实现,但是在查阅了许多资料之后,我发现事实上这玩意儿是一个误解,Android原生支持的并不是这样的。
Android原生支持的模式叫Translucent,实际上是一种全屏模式。仔细看下图,状态栏的颜色其实是在Activity的背景色上加了层遮罩,也就是说Activity不像以前那样被限制在导航栏和状态栏之间,而是全屏显示。
想开启Translucent模式很简单,只要在Theme里将android:windowTranslucentStatus
属性给设为True即可。 下面是我自定义的Theme:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#4284F3</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
</resources>
效果呢就如图所示了:
看到了吧,状态栏的颜色和Actionbar的颜色并不一样,而是和Activity的背景色一样都是白色的,只不过多了一层渐变的遮罩,而且仔细看的话,状态栏那似乎有点字在后面,那其实是“Hello World”,因为Activity是全屏嘛,所以TextView就不像以前那样在Actionbar下面了,而是在屏幕的最上面,解决这个问题的方法是在Activity的布局文件中加一句android:fitsSystemWindows="true"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:fitsSystemWindows="true">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
这样Hello World就能正常显示了。
设置状态栏颜色
如果想实现文章开头的那种效果,我们需要用到一个开源库SystemBarTint,使用时只要在Activity的onCreate中加入:
SystemBarTintManager tintManager = new SystemBarTintManager(this);
// enable status bar tint
tintManager.setStatusBarTintEnabled(true);
tintManager.setTintColor(Color.parseColor("#4284F3"));
这个库还支持设置导航栏的颜色,非常方便。
这是在Android 4.4里实现的方法,如果在Android 5.0以上的系统中,我们有更方便的方法,因为系统提供的Material主题里提供设状态栏的标签,具体介绍见使用Material的主题