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

Android 應用中實現半透明效果的多種方案

編輯:關於 Android 程式設計

Android 應用中實現半透明效果的幾種方案

無論是 Activity 還是普通 View,Android 都提供了多種方式來實現透明或半透明效果。下面分別介紹。

方案一:自定義 Activity 樣式

首先在 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 中定義顏色:

<color name="transparent_background">#50000000</color>

這裡 #50000000 的開頭兩位是透明度參數,取值從 00 到 ff(由全透明到全不透明),後六位才是顏色值。

然後在 AndroidManifest.xml 中為 Activity 指定主題:

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

最後在 Java 代碼中也可以通過 setTheme 應用樣式:

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

方案二:繼承系統內建的半透明主題

Android 自帶了一個透明主題 android:style/Theme.Translucent。想實現透明效果,直接為 Activity 設置該主題即可;若想實現半透明,只需繼承它並重寫相關屬性:

<style name="Theme.Translucent" parent="android:style/Theme.Translucent">
  <item name="android:windowBackground">@color/translucent_background</item>
  <item name="android:colorForeground">#fff</item>
</style>

在清單文件中引用即可:

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

方案三:讓 View(如按鈕)半透明

把 Button 或 ImageButton 的背景設置為半透明或全透明:

<Button android:background="#e0000000" ... />  <!-- 半透明 -->
<Button android:background="#00000000" ... />  <!-- 全透明 -->

顏色與不透明度(alpha)以十六進制表示,順序為 AABBGGRR,其中 AA 是 alpha(00 全透明、ff 全不透明),BB、GG、RR 分別是藍、綠、紅。例如要疊加一層 50% 不透明的藍色,可寫成 #7fff0000。

方案四:直接設置背景圖的透明度

這是最簡單的一種做法,只需在代碼中拿到 View 並調用 setAlpha:

View v = findViewById(R.id.content);
v.getBackground().setAlpha(100); // 0~255,值越小越透明
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved