Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ApiDemos 解析(16):App → Activity → Translucent 半透明視窗

編輯:Android 開發教學

Activity 分類的最後幾個例子都在示範半透明 Activity,程式碼大同小異。核心概念只有一個:半透明效果是透過 Style 與 Theme 達成的,而不是靠程式碼。

在 AndroidManifest 中套用主題

先看 TranslucentActivity 的宣告:

<activity android:name=".app.TranslucentActivity"
    android:label="@string/activity_translucent"
    android:theme="@style/Theme.Translucent">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.SAMPLE_CODE" />
    </intent-filter>
</activity>

關鍵是 android:theme="@style/Theme.Translucent" 這一行,它把 Activity 的視窗外觀整個換掉。

主題定義

這個主題寫在 res/styles.xml:

<!-- 一個帶半透明背景的主題。這裡明確指定它繼承系統的半透明主題,
     系統主題已經把相關屬性設定妥當。 -->
<style name="Theme.Translucent" parent="android:style/Theme.Translucent">
    <item name="android:windowBackground">@drawable/translucent_background</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:colorForeground">#fff</item>
</style>

它透過繼承系統的 android:style/Theme.Translucent,再對個別屬性做調整。其中 @drawable/translucent_background 定義在 Colors.xml,顏色值為 #e0000000。

看懂那個八位數顏色

#e0000000 之所以能產生半透明,關鍵在於它是 ARGB 格式而非 RGB:前兩個字元 e0 是 alpha 通道(十進制 224,約 88% 不透明),後六位 000000 才是黑色。也就是說,這是一層「接近不透明的黑紗」,背後畫面會隱約透出。

把透明度調成 ff 就是完全不透明,調成 00 就是全透明。理解了這個結構,你就能自由設計出各種層次感的視窗——而這一切都不需要動到一行 Java 程式碼,這正是 Android 資源系統把外觀與邏輯分離的價值所在。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved