1. 程式人生 > >Android實現暗透明背景的頁面

Android實現暗透明背景的頁面

專案要求做一個對話方塊樣式的頁面,僅頁面上的文字和按鈕可見,背景效果和對話方塊類似。下面看看怎麼實現:

方案一:
首先實現一個繼承自對話方塊樣式的主題:

    <style name="DarkTransParent" parent="android:style/Theme.Dialog">
        <item name="android:background">@android:color/transparent</item>
        <item name="android:windowBackground">@android:color/transparent</item
> <item name="android:windowNoTitle">true</item> <item name="android:windowCloseOnTouchOutside">false</item> </style>

@android:color/transparent的值為#00000000。前兩個00表示透明度,後6位為RGB值。#00000000表示全透明的黑色。

然後把這個主題應用到activity:

        <activity
            android:name=".activity.TestActivity"
android:theme="@style/DarkTransParent" />

這個activity不用做別的設定,佈局檔案裡僅包含一個TextView和一個Button。
如果在佈局檔案裡給它們設定了背景色,則背景色也會顯示出來。

效果如下:

但是這個方法有缺點:
1. 頁面佈局會被自動調整,不易控制。
2. 背景的暗色不好改。

所以嘗試了一種新的方案:

方案二:
繼承系統的透明主題,然後自定義windowBackground屬性:

    <style name="DarkTransParent" parent="android:style/Theme.Translucent"
>
<item name="android:windowBackground">@color/lock_bg</item> </style>

看下Theme.Translucent的定義:

    <style name="Theme.Translucent">
        <item name="windowBackground">@color/transparent</item>
        <item name="colorBackgroundCacheHint">@null</item>
        <item name="windowIsTranslucent">true</item>
        <!-- Note that we use the base animation style here (that is no
             animations) because we really have no idea how this kind of
             activity will be used. -->
        <item name="windowAnimationStyle">@style/Animation</item>
    </style>

然後,lock_bg即為我們想要設定的背景的顏色,我們可以在colors.xml中自定義其值:

 <color name="lock_bg">#cc000000</color>

然後把這個主題應用到activity即可:

        <activity
            android:name=".activity.TestActivity"
            android:theme="@style/DarkTransParent" />