1. 程式人生 > >Android 4.4跟Android 5.0浸入式狀態列的實現

Android 4.4跟Android 5.0浸入式狀態列的實現

  1. What:浸入式狀態列作為一個非常優秀的設計方案受到大家的熱捧,Android為了迎合趨勢,也添加了浸入式狀態列。但是Android4.4系統是市場佔有率使得我們必需在Android 4.4上面也要實現浸入式。
  2. How:在5.0系統上面實現浸入式比較簡單,Material Design給我們提供了方案。
//設計狀態列的顏色
 <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
如果希望狀態列可以被圖案填充,可以設定Activity的theme屬性如下:
  <style name="MainTheme"
parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="android:windowTranslucentStatus"
>true</item> <item name="android:windowDrawsSystemBarBackgrounds">true</item> <item name="android:statusBarColor">@android:color/transparent</item> </style>
 但是在4.4系統上面,以上程式碼就不行了,用了你會發現狀態列保持系統本身風格了,此時,你需要在values-v19(你們知道它是適配19也就是Android 4.4系統的哦)中新增styles檔案,新增程式碼如下:
 <style name="MainTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowTranslucentStatus">true</item>
    </style>
然後執行在Android 4.4的手機上你會發現為什麼我的標題欄會向上移了,雖然狀態列浸入了,但是我的狀態列不對了,此時你需要將你的標題欄的寬度增加(加上狀態列的高度),以下介紹一個簡單的實現方案:
//我將標題欄封裝了一下,添加了一個paddingTop的屬性
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/coffee"
    android:orientation="vertical"
    android:paddingTop="@dimen/statu_bar_height"
    >
    <TextView
        android:id="@+id/titleBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/title_bar_height"
        android:background="@color/coffee"/>
</LinearLayout>

上面的status_bar_height屬性有什麼用呢?

//values dimens中的定義
 <dimen name="statu_bar_height">0dp</dimen>
//values-v19 dimens中的定義,(這個高度可以具體計算的,我就沒算了,嘿嘿)
 <dimen name="statu_bar_height">22dp</dimen>

執行一下之後發現在4.4跟5.0上面標題欄都是浸入式了。
3. Why:為什麼會這樣呢?我的理解是4.4系統的手機他只是將標題欄上移了而不是填充上去,所以會造成標題欄的位置不對了。
Tips:使用該方案的時候Layout中不能新增以下屬性,否則4.4當中的狀態列就會變成一根白條:

android:fitsSystemWindows="true"

廣告時間:大神帶你飛,stay4it.com。報我名字給優惠哦!!!