萬盛學電腦網

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

Android Drawable 類型全解析:從 AnimationDrawable 到 StateListDrawable

Drawable 是 Android 視覺呈現的基礎抽象,android.graphics.drawable 包下提供 20+ 子類,覆蓋圖片、形狀、動畫、狀態、組合等場景。本文系統梳理核心 Drawable 類型的特點、用法與選型指南,助力 UI 開發精準用圖。

核心 Drawable 體系圖譜

Drawable (抽象基類)
├── BitmapDrawable          // 位圖圖片
├── ShapeDrawable           // 基礎幾何形狀
│   ├── RectShape
│   ├── OvalShape
│   ├── RoundRectShape
│   └── PathShape
├── GradientDrawable        // 漸變形狀 (XML shape 標籤實際類)
├── ColorDrawable           // 純色填充
├── NinePatchDrawable       // .9.png 九宮格拉伸
├── VectorDrawable          // 矢量圖 (API 21+)
│   └── AnimatedVectorDrawable // 矢量動畫
├── AnimationDrawable       // 幀動畫
├── StateListDrawable       // 狀態選擇器
├── LevelListDrawable       // 等級列表
├── LayerDrawable           // 圖層疊加
├── InsetDrawable           // 內縮邊距
├── ScaleDrawable           // 縮放容器
├── ClipDrawable            // 裁剪容器
├── RotateDrawable          // 旋轉容器
├── TransitionDrawable      // 淡入淡出過渡
├── RippleDrawable          // 水波紋效果 (API 21+)
└── AdaptiveIconDrawable    // 自適應圖標 (API 26+)

高頻使用類型深度解析

1. AnimationDrawable - 幀動畫

適用場景:簡易幀動畫(加載動畫、表情包、引導頁)

XML 定義 (res/drawable/anim_loading.xml):

<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="false"> <!-- true=播放一次,false=循環 -->
    <item android:drawable="@drawable/frame_0" android:duration="100" />
    <item android:drawable="@drawable/frame_1" android:duration="100" />
    <item android:drawable="@drawable/frame_2" android:duration="100" />
    <!-- 更多幀... -->
</animation-list>

代碼控制:

ImageView img = findViewById(R.id.iv_loading);
img.setBackgroundResource(R.drawable.anim_loading);
AnimationDrawable anim = (AnimationDrawable) img.getBackground();
anim.start(); // 開始
// anim.stop(); // 停止
// anim.selectDrawable(index); // 跳轉指定幀

注意:不可在 onCreate 中直接 start(),需在 onWindowFocusChanged(true) 或 post(Runnable) 中啟動,否則僅顯示第一幀。

2. GradientDrawable (XML <shape>) - 最通用的形狀繪製

XML 完整屬性 (res/drawable/bg_button.xml):

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle"> <!-- rectangle/oval/line/ring -->
    
    <!-- 實心顏色 -->
    <solid android:color="@color/colorPrimary" />
    
    <!-- 漸變 (三種類型) -->
    <gradient
        android:type="linear" <!-- linear/radial/sweep -->
        android:startColor="#FF0000"
        android:endColor="#00FF00"
        android:angle="45" /> <!-- linear 時生效,45度倍數 -->
    
    <!-- 描邊 -->
    <stroke
        android:width="2dp"
        android:color="@color/white"
        android:dashWidth="4dp" <!-- 虛線寬度 -->
        android:dashGap="2dp" /> <!-- 虛線間隙 -->
    
    <!-- 圓角 (矩形專用) -->
    <corners
        android:radius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="0dp"
        android:bottomLeftRadius="0dp"
        android:bottomRightRadius="8dp" />
    
    <!-- 內邊距 (內容區域邊距) -->
    <padding
        android:left="16dp"
        android:top="8dp"
        android:right="16dp"
        android:bottom="8dp" />
    
    <!-- 尺寸 (建議不固定,由 View 決定) -->
    <size
        android:width="100dp"
        android:height="40dp" />
</shape>

3. StateListDrawable (XML <selector>) - 狀態驅動外觀

核心用途:按鈕按下/聚焦/禁用/選中等狀態切換背景

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <!-- 順序很重要:從特定到通用,最後匹配的生效 -->
    <item android:state_pressed="true" android:drawable="@drawable/bg_pressed" />
    <item android:state_focused="true" android:drawable="@drawable/bg_focused" />
    <item android:state_selected="true" android:drawable="@drawable/bg_selected" />
    <item android:state_enabled="false" android:drawable="@drawable/bg_disabled" />
    <item android:state_checked="true" android:drawable="@drawable/bg_checked" /> <!-- CheckBox/RadioButton -->
    <item android:drawable="@drawable/bg_normal" /> <!-- 默認狀態 -->
</selector>

代碼動態構建:

StateListDrawable selector = new StateListDrawable();
selector.addState(new int[]{android.R.attr.state_pressed}, pressedDrawable);
selector.addState(new int[]{android.R.attr.state_focused}, focusedDrawable);
selector.addState(new int[]{}, normalDrawable); // 空數組 = 默認
button.setBackground(selector);

4. LayerDrawable - 多圖層疊加組合

XML 定義 (res/drawable/layer_badge.xml):

<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
    <!-- 底層:背景 -->
    <item android:drawable="@drawable/bg_icon" />
    
    <!-- 中層:圖標 (可指定邊距定位) -->
    <item
        android:drawable="@drawable/ic_notification"
        android:left="4dp"
        android:top="4dp"
        android:right="4dp"
        android:bottom="4dp" />
    
    <!-- 頂層:紅點/角標 (右上角定位) -->
    <item
        android:drawable="@drawable/badge_red_dot"
        android:gravity="top|end"
        android:right="2dp"
        android:top="2dp" />
</layer-list>

5. VectorDrawable & AnimatedVectorDrawable - 矢量圖標準

優勢:無限縮放不失真、文件極小、支持路徑動畫、API 14+ 通過 Support Library 兼容

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2z" />
</vector>

6. RippleDrawable - Material Design 水波紋

<ripple xmlns:android="https://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight"> <!-- 水波紋顏色 -->
    <item android:id="@android:id/mask">
        <shape android:shape="oval">
            <solid android:color="@android:color/white" /> <!-- 蒙版形狀決定波紋範圍 -->
        </shape>
    </item>
    <item android:drawable="@drawable/bg_button_normal" /> <!-- 背景 -->
</ripple>

選型決策表

需求場景推薦 Drawable備選方案
靜態圖片 (PNG/JPG/WebP)BitmapDrawable (直接引用)VectorDrawable (矢量源)
按鈕背景 (多狀態)StateListDrawable (<selector>)RippleDrawable (API 21+)
圓角矩形/圓形/橢圓背景GradientDrawable (<shape>)XML shape + LayerDrawable
簡易幀動畫AnimationDrawableAnimatedVectorDrawable / Lottie
圖標+紅點/數字角標LayerDrawable自定義 View 繪製
.9.png 九宮格拉伸NinePatchDrawableGradientDrawable 圓角替代
進度條/求職器可視化ClipDrawable / ScaleDrawable自定義 View + Canvas
淡入淡出圖片切換TransitionDrawableCrossfade Drawable / Glide 動畫

性能與內存最佳實踐

  1. 優先 VectorDrawable:圖標類資源首選矢量,減少多密度圖片包體積
  2. 複用 Drawable.ConstantState:相同配置的 Drawable 共享 ConstantState,mutate() 後獨立狀態
  3. 避免大 Bitmap 直接做背景:使用 inSampleSize 縮放或 Glide 加載至 ImageView
  4. 及時回收:drawable.setCallback(null) 解除 View 引用,大圖手動 bitmap.recycle() (API 21-)
  5. 啟用硬件加速:大多數 Drawable 操作受益於 GPU 渲染,少數不支持操作需關閉層類型

深度理解 Drawable 體系,能讓您在 UI 實現中「用對工具、寫出高性能、易維護」的視覺代碼,也是通往高級 UI 工程師的必經之路。

copyright © 萬盛學電腦網 all rights reserved