Android 5.0 (API 21) 及以上,`Button` 默認帶有 **Material Design 陰影(StateListAnimator + elevation)**,視覺上呈現「底部重影/立體感」,與設計稿不符。
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stateListAnimator="@null" /> <!-- 關鍵:禁用狀態動畫/陰影 -->
Button btn = findViewById(R.id.btn);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
btn.setStateListAnimator(null);
// 或 btn.setElevation(0); // 僅移除陰影高度,保留點擊動畫
}
<!-- res/values-v21/styles.xml -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:buttonStyle">@style/FlatButton</item>
</style>
<style name="FlatButton" parent="Widget.AppCompat.Button">
<item name="android:stateListAnimator">@null</item>
<item name="android:background">@drawable/btn_bg_flat</item> <!-- 自定義無陰影背景 -->
</style>
| 方案 | 適用場景 | 副作用 |
|---|---|---|
| `stateListAnimator="@null"` | 單個按鈕快速修復 | 無點擊縮放/顏色變化動畫 |
| 代碼 `setStateListAnimator(null)` | 動態創建/條件控制 | 同上 |
| 主題統一覆蓋 | 整個 App 風格扁平化 | 需提供自定義背景 drawable |
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape><solid android:color="#DDDDDD"/></shape></item>
<item android:state_focused="true">
<shape><solid android:color="#EEEEEE"/></shape></item>
<item>
<shape><solid android:color="#FFFFFF"/></shape></item>
</selector>
**Material Design 陰影是 API 21+ 默認行為,`stateListAnimator="@null"` 一行即可消除,全局風格建議主題覆蓋。**