在 KitKat以上版本中使用Translucent將Navigation Bar透明化
Android 從 4.4(KitKat) 開始提供了一個視覺上的提升,讓最上方的狀態欄 (Status Bar) 以及最下方的導航欄 (Navigation Bar) 可以被透明化,并讓 APP 的內容可以往上下延伸,使整個畫面的可被利用度大幅提升。
從 3.0 (honeycomb) 開始,Navigation Bar采用虛擬鍵,一直都占據一塊不小的空間,對很多人來說,整個屏幕無法充利用,是一件相當痛苦的事情。也因此,有些人會刻意去挑選仍維持著實體鍵設計的手機。
而 Google 似乎也意識到這個狀況,從 4.4 (KitKat) 提供了開發者一個新的作法,讓我們可以把導航欄 (Navigation Bar)給透明化,并讓內容延伸到該處,甚至是狀態列 (Status Bar) 也可以被設定透明,這樣再搭配 Action Bar 的配色,可以像上圖一般,讓整個 APP 更顯得一致。
那我們就看看是如何實現的吧:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Window window = getWindow(); // Translucent status bar window.setFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // Translucent navigation bar window.setFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); }
的確,代碼就是這么短,一行設定Status Bar、一行設定Navigation Bar 。
別忘了判斷一下版本。確保4.4以下不會報錯。
再來,有個部份要稍微留意一下,如果不希望 APP 的內容被上拉到狀態列 (Status bar) 的話,要記得在介面 (Layout) XML 檔中,最外面的那層,要再加上一個屬性 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:fitsSystemWindows="true" tools:context=".MainActivity" > <!-- Content --> </RelativeLayout>
在界面的根層加入 android:fitsSystemWindows=”true” 這個屬性,這樣就可以讓內容界面從 Action Bar 下方開始。
再來,若我們的 APP 可以從 4.4 (KitKat) 開始支持,那其實可以直接從 style 去進行設定,我們可以在官網上看到對透明化的說明里,官方提供了兩種 no title 的主題風格可以讓我們使用,分別如下
Theme.Holo.Light.NoActionBar.TranslucentDecor
Theme.Holo.NoActionBar.TranslucentDecor
這樣我們就可以做出全屏幕的APP。
如果我們希望可以維持Action Bar的存在,那只需要繼承一般的主題,并在主題中分別加入兩個屬性值即可
<style name="AppTheme" parent="AppBaseTheme"> <!-- Status Bar --> <item name="android:windowTranslucentStatus">true</item> <!-- Navigation Bar --> <item name="android:windowTranslucentNavigation">true</item> </style>
跟java代碼方式一樣,也是兩行完成,上面一行是設定Status Bar、下面一行是設定Navigation Bar 。別忘了,如果不希望內容被 Action Bar 壓住,那先前提及的 Layout 屬性 android:fitsSystemWindows=”true” 要設置到。
其實以現在的狀況來說,通過java代碼方式去設定是最安全的,畢竟目前絕大部份的裝置都還未被升級到 4.4 (KitKat)。