Shape 定義幾何圖形,Selector 根據狀態切換 Drawable,兩者結合可實現豐富的按鈕、卡片、輸入框背景效果,且無需圖片資源,包體積極小、縮放無失真。本文系統講解 Shape 五大子標簽、Selector 狀態屬性、實戰按鈕背景與圖片遮罩案例。
| 標簽 | 核心屬性 | 作用 |
|---|---|---|
<solid> | android:color | 填充顏色 |
<gradient> | startColor, endColor, angle (45倍數), type (linear/radial/sweep), gradientRadius (radial必填) | 漸變填充 |
<stroke> | width, color, dashWidth, dashGap | 描邊,支援虛線 |
<corners> | radius, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius | 圓角,可單獨控制四角 |
<padding> | left/top/right/bottom | 內容邊距,影響文字/圖標位置 |
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<gradient
android:type="radial"
android:gradientRadius="50"
android:startColor="#ff8c00"
android:endColor="#FFFFFF" />
<stroke android:width="2dp" android:color="#dcdcdc"
android:dashWidth="5dp" android:dashGap="3dp" />
<corners android:radius="5dp" />
<padding android:left="10dp" android:top="10dp"
android:right="10dp" android:bottom="10dp" />
</shape>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<solid android:color="#ff6600" />
<stroke android:width="2dp" android:color="#cc5500" />
<corners android:radius="5dp" />
<padding android:left="10dp" android:top="10dp"
android:right="10dp" android:bottom="10dp" />
</shape>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_bg_pressed" />
<item android:state_enabled="false" android:drawable="@drawable/btn_bg_disabled" />
<item android:drawable="@drawable/btn_bg_normal" /> <!-- 默認狀態放最後 -->
</selector>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交"
android:background="@drawable/btn_bg" />
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<solid android:color="#ff9d77" />
<stroke android:width="2dp" android:color="#fad3cf" />
<corners
android:topLeftRadius="5dp"
android:topRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp" />
<padding android:left="10dp" android:top="10dp"
android:right="10dp" android:bottom="10dp" />
</shape>
使用方式:imageView.setForeground(ContextCompat.getDrawable(context, R.drawable.shape_image_mask)) 或 XML android:foreground。
state_pressed、state_focused、state_selected、state_checked、state_enabled、state_window_focused、state_activated (API 11+)、state_hovered (API 14+)<layer-list> 實現圖標+背景疊加。<ripple> 替代 Selector 實現 Material Design 水波紋。掌握 Shape + Selector 組合,能以極低成本實現 90% 以上的 UI 背景狀態效果,是 Android UI 開發必備基本功。