目錄
這是很方便的一個操作
給控制設置附加圖片,這類需求在實際開發中使用頻率很高,例如下面:
- 用RadioGroup 方式實現需求是最方便的,圖片可以用 RadioButton 的 DrawableTop 添加。

- 放大鏡小圖標通過 EditText 的 DrawableLeft 方式實現。
以上的需求有多種方式可以實現,但在我看來,對於提示性的小圖標,View&View.setCompoundDrawables()的實現方式,明顯優於 View+ImageView。
操作步驟
View 添加 CompoundDrawables
一個View 可以添加四個 CompoundDrawables
android:drawableLeft=""
android:drawableRight=""
android:drawableTop=""
android:drawableBottom=""
代碼中可以也有對應的方法:
//拿到圖片
Drawable drawable = getResources().getDrawable(R.drawable.xxx);
//設置大小,注意默認的是 px, UI 圖上的 dp 單位需要轉換
drawable.setBounds(0, 0, width, height);
//給View左邊添加一個圖片
view.setCompoundDrawables(drawable,null, null, null);
View 和 CompoundDrawable 之間的間距控制
xml 佈局中設置:
android:drawablePadding=""
代碼中設置:
//注意默認的是 px, UI 圖上的 dp 單位需要轉換
view.setCompoundDrawablePadding();
CompoundDrawable 的大小控制
CompoundDrawable 的大小在佈局上沒有相關的屬性,只能通過代碼設置:
drawable.setBounds(0, 0, width, height);
最後
一個非常基礎,但是很有用的知識點,分享給你們,大家有什麼好用的小技巧,熱烈歡迎評論分享出來吶!
好啦,我們下篇文章見。喜歡不要忘記給作者點個贊,或者分享給你的小夥伴哦!
