Android 沉浸式體驗

沉浸式體驗

Android 4.4 Android 5.5

圖中所示就是Android 4.4之後被不少人稱之爲沉浸式體驗的典型場景,即狀態欄和ActionBar是同一種顏色;一度我覺得這是官方支持的,只須要幾句簡單的設置就能夠實現,可是在查閱了許多資料以後,我發現事實上這玩意兒是一個誤解,Android原生支持的並非這樣的。html

Android原生支持的模式叫Translucent,其實是一種全屏模式。仔細看下圖,狀態欄的顏色實際上是在Activity的背景色上加了層遮罩,也就是說Activity不像之前那樣被限制在導航欄和狀態欄之間,而是全屏顯示。java

想開啓Translucent模式很簡單,只要在Theme裏將android:windowTranslucentStatus屬性給設爲True便可。 下面是我自定義的Theme:android

<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>

效果呢就如圖所示了:git

看到了吧,狀態欄的顏色和Actionbar的顏色並不同,而是和Activity的背景色同樣都是白色的,只不過多了一層漸變的遮罩,並且仔細看的話,狀態欄那彷佛有點字在後面,那實際上是「Hello World」,由於Activity是全屏嘛,因此TextView就不像之前那樣在Actionbar下面了,而是在屏幕的最上面,解決這個問題的方法是在Activity的佈局文件中加一句android:fitsSystemWindows="true"github

<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就能正常顯示了。app

設置狀態欄顏色

若是想實現文章開頭的那種效果,咱們須要用到一個開源庫SystemBarTint,使用時只要在Activity的onCreate中加入:佈局

SystemBarTintManager tintManager = new SystemBarTintManager(this);
// enable status bar tint
tintManager.setStatusBarTintEnabled(true);
tintManager.setTintColor(Color.parseColor("#4284F3"));

這個庫還支持設置導航欄的顏色,很是方便。this

這是在Android 4.4裏實現的方法,若是在Android 5.0以上的系統中,咱們有更方便的方法,由於系統提供的Material主題裏提供設狀態欄的標籤,具體介紹見使用Material的主題code

相關文章
相關標籤/搜索