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

Activity 透明與半透明效果的兩種實作方式

編輯:關於 Android 程式設計

做浮上式視窗、自訂彈窗時,常需要讓 Activity 變成透明或半透明,好把底下的畫面透出來。Android 上實作方式不只一種,本文整理兩套可用方案,並說明關鍵參數的意義。

方法一:Theme 樣式 + 視窗屬性

先在 res/values 下建立 styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="translucent">
        <item name="android:windowBackground">@color/translucent_background</item>
        <item name="android:windowIsTranslucent">true</item>
    </style>
</resources>

同目錄下再建 colors.xml:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <color name="translucent_background">#60000000</color>
</resources>

設定寫好之後,得告訴哪個 Activity 要用它。在 AndroidManifest.xml 中找到要跳出的 Activity,加上 theme:

android:theme="@style/translucent"

這時候 Activity 確實透明了。但問題馬上出現:layout 裡的 button 還是不透明,看起來很突兀。要讓視窗內的元件也跟著半透明,就得去設視窗屬性:

Window window = getWindow();
WindowManager.LayoutParams wl = window.getAttributes();
wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
wl.alpha = 0.6f;  // 這句就是設置視窗裡元件的透明度
window.setAttributes(wl);

其中 alpha 就是透明度參數:0.0 全透明、1.0 完全不透明。

方法二:精簡版的樣式定義

其實單靠樣式就能做出半透明效果,不需要繞太多彎。在 res/values/styles.xml:

<resources>
    <style name="Transparent">
        <item name="android:windowBackground">@color/transparent_background</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">@+android:style/Animation.Translucent</item>
    </style>
</resources>

對應的 res/values/color.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="transparent_background">#50000000</color>
</resources>

這裡有個很多人搞不清楚的細節:#50000000 中前兩碼是透明度(從 00 到 FF,00 全透明、FF 完全不透明),後六碼才是真正的 RGB 顏色值。

接著在 manifest 註冊:

<activity android:name=".TransparentActivity" android:theme="@style/Transparent">
</activity>

Java 端也可以在建 Activity 時動態套用:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.Transparent);
    setContentView(R.layout.transparent);
}

兩種方法的取捨

方法一的好處是控制粒度細,能單獨調整視窗整體透明度,適合需要「整個視窗連元件一起變淡」的場景。方法二更輕巧,改動集中在資源檔,適合只是想要一個半透明浮層的情況。實務上兩者也可以併用:先用樣式把 Activity 變透明,再用視窗屬性微調 alpha 到你滿意的程度。

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