1. 程式人生 > >Android TextView 動態設定DrawableLeft

Android TextView 動態設定DrawableLeft

Android TextView 在xml中在新增一個文字的左右圖片很方便。

android:drawableLeft="@mipmap/icon_orange_sign"

實際應用當中需要動態設定的時候:TextView 提供了兩種方法:

setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom),及
setCompoundDrawables(left, top, right, bottom)它們的意思是設定Drawable顯示在text的左、上、右、下位置。
但是兩者有些區別:
setCompoundDrawables 畫的drawable的寬高是按drawable.setBound()設定的寬高,
所以才有The Drawables must already have had setBounds(Rect) called,即使用之前必須使用Drawable.setBounds設定Drawable的長寬。

而setCompoundDrawablesWithIntrinsicBounds是畫的drawable的寬高是按drawable固定的寬高,
所以才有The Drawables’ bounds will be set to their intrinsic bounds.即通過getIntrinsicWidth()與getIntrinsicHeight()獲得。
一般,建議使用setCompoundDrawablesWithIntrinsicBounds,這樣你即無需設定Drawables的bounds了。

TextView textDrawable = (TextView) findViewById(R.id.text_drawable);

Drawable drawableLeft = getResources().getDrawable(
R.drawable.ic_launcher);

textDrawable.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
null, null, null);
textDrawable.setCompoundDrawablePadding(4);