Android 沉浸式体验

本文详细介绍了Android中所谓的沉浸式体验,并解释了其与Translucent模式的区别。通过自定义Theme和使用SystemBarTint库,可以轻松实现状态栏及导航栏的颜色定制。

沉浸式体验

Android 4.4Android 5.5

图中所示就是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的主题

转载于:https://my.oschina.net/chasec/blog/501001

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值