Android沉浸式UI實現及原理

沉浸式體驗

首先別吐槽沉浸式這個名詞吧,畢竟這各名字是廣為人知并且比透明狀態欄加透明導航欄更酷。充分使用整個屏幕將這2個系統視圖融入自己APP也算沉浸式體驗吧。

首先2個名詞:
StatusBar

Paste_Image.png

NavigationBar
Paste_Image.png

下面是Google的官方標準模版:

未標題-1.jpg

在官方示例中:
StatusBar是一個半透明陰影,View可以伸展到其后面。
NavigationBar是純黑不能使用的。

Google提供NavigationBar的透明與使用的可能,卻沒有推薦使用。個人覺得是為了給

Paste_Image.png

Bottom navigation
做準備。這里不討論Bottom navigation的優劣(我是Bottom navigation黑)。

下面是B站的:

QQ圖片20160525195336.jpg

不可否認使用NavigationBar空間對多下巴手機是種拯救。
(Google自己推的虛擬按鍵,卻自己放棄了屏占比這一大優勢。)

好了,B站的UI就是我所期望的UI。下面我們就來實現它。

style的配置

android從4.4開始,開始支持UI使用StatusBar與NavigationBar的范圍。
所以要進行下面的配置:

在value中的styles.xml中設置

<!-- Base application theme. -->
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
</style>
<style name="AppTheme" parent="AppTheme.Base"></style>

在value-v19中的styles.xml中設置(為了兼容4.4)

<style name="AppTheme" parent="AppTheme.Base">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>

在value-v21中的styles.xml中設置

<style name="AppTheme" parent="AppTheme.Base">
    <!--透明狀態欄-->
    <item name="android:windowTranslucentStatus">true</item>
    <!--透明導航欄-->
    <item name="android:windowTranslucentNavigation">true</item> 
    <!--使狀態欄,導航欄可繪制-->
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
</style>

然后使用AppTheme這個主題,這是1個示例,應該看得出來吧。只要在你的AppTheme的v19版本和v21版本添加了相應屬性就好。

使用ToolBar

當你使用了StatusBar的部分,就不要再使用ActionBar了。
現在基本都會使用ToolBar了吧。還不會可以參考 ToolBar的使用

然后效果如下:

QQ圖片20160525195351.jpg

然后這里就有2個問題:

1. Toolbar到了StatusBar的下面(為了凸顯問題給Toolbar設了顏色)
2. View在NavigationBar下難以點擊

這2個問題也是理所應當就應該存在的。
解決方法

FitSystemWindowLayout

這里就先說結果吧,使用FitSystemWindowLayout,我為此做了很多適配工作。
這是標準界面:

QQ圖片20160525195401.jpg

這個庫提供自動適應StatusBar與NavigationBar的幾個Layout。在XML中設置即可。
這是上面標準UI的XML:

<?xml version="1.0" encoding="utf-8"?>
<com.jude.fitsystemwindowlayout.FitSystemWindowsFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:padding_status="false"http://不自動騰出StatusBar的空間,為了讓圖片在StatusBar下繪制
    tools:context="com.jude.demo.MainActivity">

    //這個ViewPager里面放的ImageView
    <com.jude.rollviewpager.RollPagerView
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        app:rollviewpager_play_delay="3000"/>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?actionBarSize"
        android:background="#0000"http://透明ToolBar
        app:theme="@style/AppTheme.Dark"
        app:margin_status="true"http://讓ToolBar去適應StatusBar
        />

    <ScrollView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:padding_navigation="true"http://只對可滑動View有效的屬性,自動增加底部內Padding
        android:layout_marginTop="300dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/Base.TextAppearance.AppCompat.Display3"
            android:text="A\nB\nC\nD\nE\nF\nG"/>
    </ScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:margin_navigation="true"http://讓FAB去適應NavigationBar
        android:src="@android:drawable/ic_dialog_email" />

</com.jude.fitsystemwindowlayout.FitSystemWindowsFrameLayout>

FitSystemWindow的原理

Android4.4與Android5.0的Insets處理機制完全不同。

Android 5.0的機制:

ViewRootImpl.java中掌管View繪制的函數。

private void performTraversals() {
    ……
    dispatchApplyInsets(host);
    ……
    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
    ……
    performLayout(lp, desiredWindowWidth, desiredWindowHeight);
    ……
    performDraw();
}

void dispatchApplyInsets(View host) {
    host.dispatchApplyWindowInsets(getWindowInsets(true /* forceConstruct */));
}

SystemBar的尺寸在WindowInsets 中表示出來,比如Insets:(0, 63 , 0, 126)。表示StatusBar高度63,NavigationBar高度126.
dispatchApplyWindowInsets 將WindowInsets 從View樹頂部開始分發。

//View.java 代碼經過精簡
public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
    if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
        return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
    } else {
        return onApplyWindowInsets(insets);
    }
}
--------------------------------------------------------------------
//ViewGroup.java
@Override
public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
    insets = super.dispatchApplyWindowInsets(insets);
    if (!insets.isConsumed()) {
        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            insets = getChildAt(i).dispatchApplyWindowInsets(insets);
            if (insets.isConsumed()) {
                break;
            }
        }
    }
    return insets;
}

這個方法很簡單。在View樹中分發Insets,先序遍歷。一旦被消費就終止分發。可以看到處理WindowInsets 主要是2個方式。

自定義Insets處理方式的方法1

給目標View注冊監聽
View接收到Insets。會先判斷自己是否被注冊了監聽,監聽是指這個,在這個監聽里能夠收到Insets。并依據自己情況處理。

public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
    getListenerInfo().mOnApplyWindowInsetsListener = listener;
}

自定義Insets處理方式的方法2

重寫onApplyWindowInsets
先看看默認的實現。

//代碼經過精簡
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
    if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
        //如果fitSystemWindowsInt返回true就消耗Instes,好簡單的邏輯
        return insets.consumeSystemWindowInsets();
    }
    return insets;
}

重點來了fitSystemWindowsInt.它實質性的判斷并設置了Padding。

private boolean fitSystemWindowsInt(Rect insets) {
    //如果設置了FITS_SYSTEM_WINDOWS這個flag
    if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
        mUserPaddingStart = UNDEFINED_PADDING;
        mUserPaddingEnd = UNDEFINED_PADDING;
        Rect localInsets = sThreadLocal.get();
        if (localInsets == null) {
            localInsets = new Rect();
            sThreadLocal.set(localInsets);
        }
        
        //computeFitSystemWindows主要就是localInsets=insets。并清空insets
        boolean res = computeFitSystemWindows(insets, localInsets);
        
        mUserPaddingLeftInitial = localInsets.left;
        mUserPaddingRightInitial = localInsets.right;
        
        //直接應用這個Insets到padding
        internalSetPadding(localInsets.left, localInsets.top,
                localInsets.right, localInsets.bottom);
        return res;
    }
    return false;
}

FITS_SYSTEM_WINDOWS這個flag有2個來源:
代碼手動設置:

public void setFitsSystemWindows(boolean fitSystemWindows) {
    setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
}

在XML中設置android:fitSystemWindow="true"

 case com.android.internal.R.styleable.View_fitsSystemWindows:
     if (a.getBoolean(attr, false)) {
         viewFlagValues |= FITS_SYSTEM_WINDOWS;
         viewFlagMasks |= FITS_SYSTEM_WINDOWS;
     }
     break;

這就很明顯了。
設置了fitSystemWindow,默認就會消費掉Insets,并設置padding。如果沒有設置,會繼續遍歷直到被某個View消耗。

其實上面的代碼是精簡后的,實際上對4.4的機制做了一些兼容處理。為了便于理解刪掉了。

Android 4.4的機制:

4.4的機制比5.0簡單得多。

private void performTraversals() {
    ……
    host.fitSystemWindows(mFitSystemWindowsInsets);
    ……
    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
    ……
    performLayout(lp, desiredWindowWidth, desiredWindowHeight);
    ……
    performDraw();
}

讓DecorView執行fitSystemWindows

//ViewGroup.java
@Override
protected boolean fitSystemWindows(Rect insets) {
    boolean done = super.fitSystemWindows(insets);
    if (!done) {
        final int count = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < count; i++) {
            done = children[i].fitSystemWindows(insets);
            if (done) {
                break;
            }
        }
    }
    return done;
}
----------------------------------------------------
//View.java
//與5.0的fitSystemWindowsInt方法一樣
protected boolean fitSystemWindows(Rect insets) {
    if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
        mUserPaddingStart = UNDEFINED_PADDING;
        mUserPaddingEnd = UNDEFINED_PADDING;
        Rect localInsets = sThreadLocal.get();
        if (localInsets == null) {
            localInsets = new Rect();
            sThreadLocal.set(localInsets);
        }
        boolean res = computeFitSystemWindows(insets, localInsets);
        mUserPaddingLeftInitial = localInsets.left;
        mUserPaddingRightInitial = localInsets.right;
        internalSetPadding(localInsets.left, localInsets.top,
                localInsets.right, localInsets.bottom);
        return res;
    }
    return false;
}

分發的過程變到了這里。并且直接就應用了。
與5.0有很大不同(簡單了好多)。
重寫fitSystemWindows方法即可實現與5.0一樣的效果。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,663評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,125評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,506評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,614評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,402評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,934評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,021評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,168評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,690評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,596評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,784評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,288評論 5 357
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,027評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,404評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,662評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,398評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,743評論 2 370

推薦閱讀更多精彩內容