Android 4.4 沉浸式透明狀態欄與導航欄


Android 系統自4.2 開始 UI 上就沒多大改變,4.4 也僅僅是添加了透明狀態欄與導航欄的功能,如圖




那么如今我就來給大家解說下怎樣使用這個新特性,讓你的 app 尾隨潮流,當然假設你不在乎外觀就算了,
使用這個特性能開發出非常美麗的UI,尤其對於 google 原生系統,屏幕下方的導航欄白白占領一塊屏幕空間,看起來非常不爽



OK廢話不多講,開始講技術吧,第一種方法,在代碼設置:

  1. if(VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
  2.                                 //透明狀態欄
  3.                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
  4.                                 //透明導航欄
  5.                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
  6.                         }
直接調用上面2行代碼能夠透明,可是你會發現你的 view 跑到 actionbar 上面去了,非常明顯 google 的意圖是使你的 view 能夠占領整個屏幕,然后 狀態欄和導航欄 透明覆蓋在上面非常明顯這樣不可行。
那有沒有辦法使你的 view 保持原來大小呢?
有,你須要在這個 activity 的 layout xml 文件加入兩個屬性
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     android:layout_width="fill_parent"
  3.     android:layout_height="fill_parent"
  4.     android:gravity="center_horizontal"
  5.     
  6.     android:fitsSystemWindows="true"
  7.     android:clipToPadding="true"
  8.     
  9.     android:orientation="vertical" >
這樣狀態欄的背景就是你的 activity 的主背景,倘若actionbar 在,將會非常難看,如圖:

事實證明,google 並沒有提供一個比較好的解決方式,他的 透明狀態欄與導航欄的應用局限於,全屏閱讀文字或玩游戲那種情景,


另外一種方式, 是是設置 theme 屬性

  1. android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar.TranslucentDecor"
  2.             android:theme="@android:style/Theme.Holo.Light.NoActionBar.TranslucentDecor"
  3.             android:theme="@android:style/Theme.Holo.NoActionBar.TranslucentDecor"
復制代碼
假設你使用自定主題,僅僅需在在 values-19 文件加入下面屬性:
  1. <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">

  2.         <!-- API 19 theme customizations can go here. -->
  3.         <item name="android:windowTranslucentStatus">true</item>
  4.         <item name="android:windowTranslucentNavigation">true</item>
  5.     </style>
復制代碼

剛剛說了這個使用有局限性,只是好在有一個開源的東西
https://github.com/jgilfelt/SystemBarTint


使用這個開源庫,必須開啟透明標題欄

使用這個主題

  1. <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">

  2.         <!-- API 19 theme customizations can go here. -->
  3.         <item name="android:windowTranslucentStatus">true</item>
  4.         <item name="android:windowTranslucentNavigation">true</item>
  5.     </style>

或者在setContentView之前調用這個代碼


  1. if(VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
  2.                                 //透明狀態欄
  3.                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
  4.                                 //透明導航欄
  5.                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
  6.                         }





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM