開發中我們想實作一種帶圖示的 TextView的時候 一般會使用 TextView的drawableTop,drawableLeft,等 屬性,這個屬性是在xml檔案中定義的。
<TextView
android:id="@+id/tv_homapage"
android:paddingTop="10dp"
android:drawableTop="@mipmap/ico_home_normal"
android:textColor="@color/white"
android:gravity="center"
android:text="首頁"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
但是有時候我們想在java代碼中動态的修改 drawable的值,也就是在運作時 修改 drawable的狀态。
這個時候我們可以使用如下方法
Drawable top = getResources().getDrawable(R.drawable.image);
button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
我們動态的擷取drawable資源,然後設定給button或者 TextView,
button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
這個方法的四個參數分别是指,left ,top,right ,bottom。 也就是你要添加的 drawable圖檔相對于text的位置。
如果不想在某個位置添加圖檔則設定為null即可。
reference link