2012年3月2日

[Android] 替 TextView 加上圖示

Android 的 TextView 除了顯示文字,還可以在上、下、左、右加上圖示。
透過程式,有三種方法:

TextView#setCompoundDrawablesWithIntrinsicBounds(int, int, int, int);
TextView#setCompoundDrawablesWithIntrinsicBounds(Drawable, Drawable, Drawable, Drawable);
TextView#setCompoundDrawables(Drawable, Drawable, Drawable, Drawable);

前兩個方法會完整顯示指定的 drawable;若使用最後一個方法記得要先呼叫 Drawable#setBounds() 指定 drawable 的顯示範圍。像這樣:

aDrawable.setBounds(0, 0, 60, 60);
textView.setCompoundDrawables(aDrawable, null, null, null);