天天看點

android KitKat Translucent 4.4版本支援消息欄半透明

Android 從 4.4(KitKat) 開始提供了一個視覺上的提升,讓位在裝置最上方的狀态列 (Status Bar) 以及最下方的導航列 (Navigation Bar) 可以被透明化,并讓 APP 的内容可以往上下延伸,使整個畫面的可被利用度大幅提升

從 3.0 (honeycomb) 開始,導航列被虛拟化,一直都會占住裝置一塊不算小的空間,對很多人來說,整個畫面無法充份利用,是一件相當痛苦的事情。也是以,有些人就會刻意去挑選仍維持著實體鍵設計的裝置。

而 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 (KitKat) 以上來進行容錯。

再來,有個部份要稍微留意一下,如果不希望 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

這樣我們就可以做出全螢幕的 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>

跟程式碼一樣,也是兩行完成,上面一行是設定狀态列 (Status Bar)、下面一行是設定導航列 (Navigation Bar) 。别忘了,如果不希望内容被 Action Bar 壓住,那先前提及的 Layout 屬性 android:fitsSystemWindows=”true” 要設定到。

其實以現在的狀況來說,透過程式碼去設定是最為安全的,畢竟目前絕大部份的裝置都還未被更新到 4.4 (KitKat)。