萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android XML 實現漸層背景(Shape Drawable)教學

前言

Android 透過 Shape Drawable 的 <gradient> 標籤即可在 XML 定義線性、放射、掃射漸層,無需圖片資源即可實現豐富視覺效果。本文示範最常用的線性漸層範例與屬性對照。

基本漸層 XML (res/drawable/gradient_bg.xml)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:angle="270"
        android:startColor="#4a557c"
        android:endColor="#62c4e7" />

</shape>

套用至 View

<View
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/gradient_bg" />

Gradient 核心屬性對照

屬性說明典型值
android:type漸層類型linear (預設) / radial / sweep
android:angle線性漸層角度(須為 45 的倍數)0, 90, 180, 270
android:startColor起始顏色#RRGGBB 或 #AARRGGBB
android:endColor結束顏色同上
android:centerColor中間顏色(可選)同上
android:centerX / centerY放射漸層中心點 (0~1)0.5
android:gradientRadius放射漸層半徑(需 type=radial)100dp
android:useLevel是否作為 LevelListDrawablefalse

進階:多色漸層 (API 24+)

<gradient
    android:type="linear"
    android:angle="0"
    android:startColor="#FF0000"
    android:centerColor="#00FF00"
    android:endColor="#0000FF" />

常見應用場景

  • 按鈕背景、卡片邊框、工具列、狀態列背景。
  • 搭配 <corners> 圓角、<stroke> 邊框、<padding> 內距,構建完整元件外觀。
  • 動態調整:程式碼中取得 GradientDrawable 呼叫 setColors()、setOrientation() 實現動畫漸層。

純 XML 即可實現高效能漸層背景,減少 APK 體積並支援任意解析度縮放。

copyright © 萬盛學電腦網 all rights reserved