代碼中動態改變 TextView 的 drawableLeft,必須對 Drawable 調用 setBounds 設置寬高,否則不顯示。
Drawable drawable = getResources().getDrawable(R.drawable.new_icon);
// 關鍵:設置邊界,寬高可用內在尺寸
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
// 設置左側 drawable,其他方向傳 null
textView.setCompoundDrawables(drawable, null, null, null);
// 或保留原有其他方向
// textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
| 方法 | 特點 |
|---|---|
setCompoundDrawables(left, top, right, bottom) | 需手動 setBounds,完全控制 |
setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom) | 自動用內在尺寸,無需 setBounds,推薦 |
setCompoundDrawablesRelative(...) | 支持 RTL 佈局(start/end) |
<TextView
android:drawableLeft="@drawable/icon"
android:drawablePadding="8dp" />
記住 setBounds 或用 WithIntrinsicBounds 系列,drawable 才會正確顯示。