在 Android 開發中,常需要在按鈕上同時展示圖標與文字(如「保存」前帶磁盤圖標)。原生 Button 控件通過 XML 屬性或代碼均可輕鬆實現。
在布局文件中直接使用 drawableLeft、drawableRight、drawableTop、drawableBottom 指定圖片位置,配合 drawablePadding 控制圖文間距:
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存"
android:drawableLeft="@drawable/ic_save"
android:drawablePadding="8dp"
android:padding="12dp" />
若需在運行時根據條件動態設置,可使用 setCompoundDrawables() 或 setCompoundDrawablesRelative()(API 17+ 支持 RTL):
Button btn = findViewById(R.id.btn_save);
Drawable drawable = ContextCompat.getDrawable(this, R.drawable.ic_save);
// 必須設置 bounds,否則圖片不顯示
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
// 參數順序:左、上、右、下
btn.setCompoundDrawables(drawable, null, null, null);
btn.setCompoundDrawablePadding(dp2px(8));
drawableRight 實現「文字在左、圖標在右」的效果。StateListDrawable 實現按下/不可用等狀態下的不同圖標。app:iconGravity、app:iconPadding 等更豐富的屬性,建議優先使用。setBounds() 導致圖片不顯示。android:drawableTint 統一顏色。drawableLeft/Right 不自動翻轉,需改用 drawableStart/End 或 setCompoundDrawablesRelative()。